diff --git a/.gitignore b/.gitignore index 79d9e76d335..c7d64370069 100644 --- a/.gitignore +++ b/.gitignore @@ -19,3 +19,6 @@ build/linux/dist/*.tar.gz build/linux/*.tgz test-bin *.iml +build/windows/launch4j-* +build/windows/launcher/launch4j +build/windows/WinAVR-*.zip diff --git a/README.md b/README.md new file mode 100644 index 00000000000..0c0e4175157 --- /dev/null +++ b/README.md @@ -0,0 +1,44 @@ +Arduino +======== + +* Arduino is an open-source physical computing platform based on a simple i/o +board and a development environment that implements the Processing/Wiring +language. Arduino can be used to develop stand-alone interactive objects or +can be connected to software on your computer (e.g. Flash, Processing, MaxMSP). +The boards can be assembled by hand or purchased preassembled; the open-source +IDE can be downloaded for free. + +* For more information, see the website at: http://www.arduino.cc/ +or the forums at: http://arduino.cc/forum/ + +* To report a *bug* in the software or to request *a simple enhancement* go to: +http://github.com/arduino/Arduino/issues + +* More complex requests and technical discussion should go on the Arduino Developers +mailing list: +https://groups.google.com/a/arduino.cc/forum/#!forum/developers + +* If you're interested in modifying or extending the Arduino software, we strongly +suggest discussing your ideas on the Developers mailing list *before* starting +to work on them. That way you can coordinate with the Arduino Team and others, +giving your work a higher chance of being integrated into the official release +https://groups.google.com/a/arduino.cc/forum/#!forum/developers + +Installation +------------ +Detailed instructions are in reference/Guide_Windows.html and +reference/Guide_MacOSX.html. For Linux, see the Arduino playground: +http://www.arduino.cc/playground/Learning/Linux + +Credits +-------- +Arduino is an open source project, supported by many. + +The Arduino team is composed of Massimo Banzi, David Cuartielles, Tom Igoe, +Gianluca Martino, Daniela Antonietti, and David A. Mellis. + +Arduino uses the [GNU avr-gcc toolchain](http://gcc.gnu.org/wiki/avr-gcc), [avrdude](http://www.nongnu.org/avrdude/), [avr-libc](http://www.nongnu.org/avr-libc/), and code from +[Processing](http://www.processing.org) and [Wiring](http://wiring.org.co). + +Icon and about image designed by [ToDo](http://www.todo.to.it/) + diff --git a/app/src/processing/app/Base.java b/app/src/processing/app/Base.java index 33e8ff410aa..5d784facf6b 100644 --- a/app/src/processing/app/Base.java +++ b/app/src/processing/app/Base.java @@ -31,6 +31,9 @@ import processing.app.debug.Compiler; import processing.app.debug.Target; +import processing.app.helpers.FileUtils; +import processing.app.helpers.filefilters.OnlyDirs; +import processing.app.javax.swing.filechooser.FileNameExtensionFilter; import processing.app.tools.ZipDeflater; import processing.core.*; import static processing.app.I18n._; @@ -117,7 +120,7 @@ static public void main(String args[]) { File versionFile = getContentFile("lib/version.txt"); if (versionFile.exists()) { String version = PApplet.loadStrings(versionFile)[0]; - if (!version.equals(VERSION_NAME)) { + if (!version.equals(VERSION_NAME) && !version.equals("${version}")) { VERSION_NAME = version; RELEASE = true; } @@ -126,6 +129,10 @@ static public void main(String args[]) { e.printStackTrace(); } + // help 3rd party installers find the correct hardware path + Preferences.set("last.ide." + VERSION_NAME + ".hardwarepath", getHardwarePath()); + Preferences.set("last.ide." + VERSION_NAME + ".daterun", "" + (new Date()).getTime() / 1000); + // if (System.getProperty("mrj.version") != null) { // //String jv = System.getProperty("java.version"); // String ov = System.getProperty("os.version"); @@ -949,9 +956,10 @@ public void rebuildImportMenu(JMenu importMenu, final Editor editor) { JMenuItem addLibraryMenuItem = new JMenuItem(_("Add Library...")); addLibraryMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { - Base.this.handleAddZipLibrary(editor); + Base.this.handleAddLibrary(editor); Base.this.onBoardOrPortChange(); Base.this.rebuildImportMenu(Editor.importMenu, editor); + Base.this.rebuildExamplesMenu(Editor.examplesMenu); } }); importMenu.add(addLibraryMenuItem); @@ -1203,62 +1211,51 @@ public void actionPerformed(ActionEvent event) { boolean ifound = false; for (String potentialName : list) { - File subfolder = new File(folder, potentialName); -// File libraryFolder = new File(subfolder, "library"); -// File libraryJar = new File(libraryFolder, potentialName + ".jar"); -// // If a .jar file of the same prefix as the folder exists -// // inside the 'library' subfolder of the sketch -// if (libraryJar.exists()) { - String sanityCheck = Sketch.sanitizeName(potentialName); - if (!sanityCheck.equals(potentialName)) { - String mess = I18n.format( - _("The library \"{0}\" cannot be used.\n" + - "Library names must contain only basic letters and numbers.\n" + - "(ASCII only and no spaces, and it cannot start with a number)"), - potentialName - ); - Base.showMessage(_("Ignoring bad library name"), mess); - continue; - } + File libFolder = new File(folder, potentialName); + String sanityCheck = Sketch.sanitizeName(potentialName); + if (!sanityCheck.equals(potentialName)) { + String mess = I18n.format(_("The library \"{0}\" cannot be used.\n" + + "Library names must contain only basic letters and numbers.\n" + + "(ASCII only and no spaces, and it cannot start with a number)"), + potentialName); + Base.showMessage(_("Ignoring bad library name"), mess); + continue; + } - String libraryName = potentialName; -// // get the path for all .jar files in this code folder -// String libraryClassPath = -// Compiler.contentsToClassPath(libraryFolder); -// // grab all jars and classes from this folder, -// // and append them to the library classpath -// librariesClassPath += -// File.pathSeparatorChar + libraryClassPath; -// // need to associate each import with a library folder -// String packages[] = -// Compiler.packageListFromClassPath(libraryClassPath); - libraries.add(subfolder); + String libraryName = potentialName; + libraries.add(libFolder); + String libFolderPath = libFolder.getAbsolutePath(); try { - String packages[] = - Compiler.headerListFromIncludePath(subfolder.getAbsolutePath()); - for (String pkg : packages) { - importToLibraryTable.put(pkg, subfolder); + String headers[] = Compiler.headerListFromIncludePath(libFolderPath); + for (String header : headers) { + // Extract file name (without extension ".h") + String name = header.substring(0, header.length() - 2); + + // If the header name equals to the current library folder use it + if (libFolderPath.endsWith(name)) { + importToLibraryTable.put(header, libFolder); + continue; + } + + // If a library was already found with this header, keep it if + // the library's directory name matches the header name. + File old = importToLibraryTable.get(header); + if (old != null) { + if (old.getPath().endsWith(name)) + continue; + } + importToLibraryTable.put(header, libFolder); } } catch (IOException e) { - showWarning(_("Error"), I18n.format("Unable to list header files in {0}", subfolder), e); + showWarning(_("Error"), I18n.format( + "Unable to list header files in {0}", libFolder), e); } - JMenuItem item = new JMenuItem(libraryName); - item.addActionListener(listener); - item.setActionCommand(subfolder.getAbsolutePath()); - menu.add(item); - ifound = true; - -// XXX: DAM: should recurse here so that library folders can be nested -// } else { // not a library, but is still a folder, so recurse -// JMenu submenu = new JMenu(libraryName); -// // needs to be separate var, otherwise would set ifound to false -// boolean found = addLibraries(submenu, subfolder); -// if (found) { -// menu.add(submenu); -// ifound = true; -// } -// } + JMenuItem item = new JMenuItem(libraryName); + item.addActionListener(listener); + item.setActionCommand(libFolderPath); + menu.add(item); + ifound = true; } return ifound; } @@ -2374,24 +2371,70 @@ static protected void listFiles(String basePath, } } + public void handleAddLibrary(Editor editor) { + JFileChooser fileChooser = new JFileChooser(System.getProperty("user.home")); + fileChooser.setDialogTitle(_("Select a zip file or a folder containing the library you'd like to add")); + fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); + fileChooser.setFileFilter(new FileNameExtensionFilter(_("ZIP files or folders"), "zip")); - public void handleAddZipLibrary(Editor editor) { - String prompt = _("Select a zip file containing the library you'd like to add"); - FileDialog fd = new FileDialog(editor, prompt, FileDialog.LOAD); - fd.setDirectory(System.getProperty("user.home")); - fd.setVisible(true); + Dimension preferredSize = fileChooser.getPreferredSize(); + fileChooser.setPreferredSize(new Dimension(preferredSize.width + 200, preferredSize.height + 200)); - String directory = fd.getDirectory(); - String filename = fd.getFile(); - if (filename == null) return; + int returnVal = fileChooser.showOpenDialog(editor); + + if (returnVal != JFileChooser.APPROVE_OPTION) { + return; + } + + File sourceFile = fileChooser.getSelectedFile(); + File tmpFolder = null; - File sourceFile = new File(directory, filename); try { - ZipDeflater zipDeflater = new ZipDeflater(sourceFile, getSketchbookLibrariesFolder()); - zipDeflater.deflate(); + // unpack ZIP + if (!sourceFile.isDirectory()) { + try { + tmpFolder = FileUtils.createTempFolder(); + ZipDeflater zipDeflater = new ZipDeflater(sourceFile, tmpFolder); + zipDeflater.deflate(); + File[] foldersInTmpFolder = tmpFolder.listFiles(new OnlyDirs()); + if (foldersInTmpFolder.length != 1) { + throw new IOException(_("Zip doesn't contain a library")); + } + sourceFile = foldersInTmpFolder[0]; + } catch (IOException e) { + editor.statusError(e); + return; + } + } + + // is there a valid library? + File libFolder = sourceFile; + String libName = libFolder.getName(); + if (!Sketch.isSanitaryName(libName)) { + String mess = I18n.format(_("The library \"{0}\" cannot be used.\n" + + "Library names must contain only basic letters and numbers.\n" + + "(ASCII only and no spaces, and it cannot start with a number)"), + libName); + editor.statusError(mess); + return; + } + + // copy folder + File destinationFolder = new File(getSketchbookLibrariesFolder(), sourceFile.getName()); + if (!destinationFolder.mkdir()) { + editor.statusError(I18n.format(_("A library named {0} already exists"), sourceFile.getName())); + return; + } + try { + FileUtils.copy(sourceFile, destinationFolder); + } catch (IOException e) { + editor.statusError(e); + return; + } editor.statusNotice(_("Library added to your libraries. Check \"Import library\" menu")); - } catch (IOException e) { - editor.statusError(e); + } finally { + // delete zip created temp folder, if exists + FileUtils.recursiveDelete(tmpFolder); } } } diff --git a/app/src/processing/app/Editor.java b/app/src/processing/app/Editor.java index 4fc2d13cd44..61051f93c97 100644 --- a/app/src/processing/app/Editor.java +++ b/app/src/processing/app/Editor.java @@ -177,7 +177,7 @@ public void windowActivated(WindowEvent e) { // re-add the sub-menus that are shared by all windows fileMenu.insert(sketchbookMenu, 2); fileMenu.insert(examplesMenu, 3); - //sketchMenu.insert(importMenu, 4); + sketchMenu.insert(importMenu, 4); toolsMenu.insert(boardsMenu, numTools); toolsMenu.insert(serialMenu, numTools + 1); } @@ -188,7 +188,7 @@ public void windowDeactivated(WindowEvent e) { // System.err.println("deactivate"); // not coming through fileMenu.remove(sketchbookMenu); fileMenu.remove(examplesMenu); - //sketchMenu.remove(importMenu); + sketchMenu.remove(importMenu); toolsMenu.remove(boardsMenu); toolsMenu.remove(serialMenu); } @@ -430,6 +430,8 @@ protected void applyPreferences() { textarea.setEditable(!external); saveMenuItem.setEnabled(!external); saveAsMenuItem.setEnabled(!external); + + textarea.setDisplayLineNumbers(Preferences.getBoolean("editor.linenumbers")); TextAreaPainter painter = textarea.getPainter(); if (external) { diff --git a/app/src/processing/app/EditorStatus.java b/app/src/processing/app/EditorStatus.java index 57b7fba0ff3..fa45f02e564 100644 --- a/app/src/processing/app/EditorStatus.java +++ b/app/src/processing/app/EditorStatus.java @@ -27,6 +27,9 @@ import java.awt.event.*; import javax.swing.*; +import java.awt.datatransfer.*; +import static processing.app.I18n._; + /** * Panel just below the editing area that contains status messages. @@ -68,6 +71,7 @@ public class EditorStatus extends JPanel /*implements ActionListener*/ { JButton okButton; JTextField editField; JProgressBar progressBar; + JButton copyErrorButton; //Thread promptThread; int response; @@ -108,6 +112,7 @@ public void empty() { public void notice(String message) { mode = NOTICE; this.message = message; + copyErrorButton.setVisible(false); //update(); repaint(); } @@ -120,6 +125,7 @@ public void unnotice(String unmessage) { public void error(String message) { mode = ERR; this.message = message; + copyErrorButton.setVisible(true); repaint(); } @@ -177,6 +183,7 @@ public void progress(String message) this.message = message; progressBar.setIndeterminate(false); progressBar.setVisible(true); + copyErrorButton.setVisible(false); setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); repaint(); } @@ -189,6 +196,7 @@ public void progressIndeterminate(String message) progressBar.setIndeterminate(true); progressBar.setValue(50); progressBar.setVisible(true); + copyErrorButton.setVisible(false); setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); repaint(); } @@ -207,6 +215,7 @@ public void unprogress() if (Preferences.getBoolean("editor.beep.compile")) { Toolkit.getDefaultToolkit().beep(); } + if (progressBar == null) return; progressBar.setVisible(false); progressBar.setValue(0); setCursor(null); @@ -216,6 +225,7 @@ public void unprogress() public void progressUpdate(int value) { + if (progressBar == null) return; progressBar.setValue(value); repaint(); } @@ -438,6 +448,32 @@ public void keyTyped(KeyEvent event) { add(progressBar); progressBar.setVisible(false); + copyErrorButton = new JButton( + "" + _("Copy error") + "
" + _("to clipboard") + ""); + Font font = copyErrorButton.getFont(); + font = new Font(font.getName(), font.getStyle(), (int) (font.getSize()*0.7)); + copyErrorButton.setFont(font); + copyErrorButton.setHorizontalAlignment(JLabel.CENTER); + add(copyErrorButton); + copyErrorButton.setVisible(false); + copyErrorButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + String message=""; + if ((Preferences.getBoolean("build.verbose")) == false) { + message = " " + _("This report would have more information with") + "\n"; + message += " \"" + _("Show verbose output during compilation") + "\"\n"; + message += " " + _("enabled in File > Preferences.") + "\n"; + } + message += _("Arduino: ") + Base.VERSION_NAME + " (" + System.getProperty("os.name") + "), "; + message += _("Board: ") + "\"" + Base.getBoardPreferences().get("name") + "\"\n"; + message += editor.console.consoleTextPane.getText().trim(); + Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); + StringSelection data = new StringSelection(message); + clipboard.setContents(data, null); + Clipboard unixclipboard = Toolkit.getDefaultToolkit().getSystemSelection(); + if (unixclipboard != null) unixclipboard.setContents(data, null); + } + }); } } @@ -470,6 +506,10 @@ protected void setButtonBounds() { editField.setBounds(yesLeft - Preferences.BUTTON_WIDTH, editTop, editWidth, editHeight); progressBar.setBounds(noLeft, editTop, editWidth, editHeight); + + Dimension copyErrorButtonSize = copyErrorButton.getPreferredSize(); + copyErrorButton.setLocation(sizeW - copyErrorButtonSize.width - 5, top); + copyErrorButton.setSize(copyErrorButtonSize.width, Preferences.BUTTON_HEIGHT); } diff --git a/app/src/processing/app/Preferences.java b/app/src/processing/app/Preferences.java index 00a5989edab..e084ddde606 100644 --- a/app/src/processing/app/Preferences.java +++ b/app/src/processing/app/Preferences.java @@ -177,6 +177,7 @@ public class Preferences { JCheckBox exportSeparateBox; JCheckBox verboseCompilationBox; JCheckBox verboseUploadBox; + JCheckBox displayLineNumbersBox; JCheckBox verifyUploadBox; JCheckBox externalEditorBox; JCheckBox memoryOverrideBox; @@ -382,6 +383,15 @@ public void actionPerformed(ActionEvent e) { box.setBounds(left, top, d.width, d.height); top += d.height + GUI_BETWEEN; + // [ ] Display line numbers + + displayLineNumbersBox = new JCheckBox(_("Display line numbers")); + pain.add(displayLineNumbersBox); + d = displayLineNumbersBox.getPreferredSize(); + displayLineNumbersBox.setBounds(left, top, d.width + 10, d.height); + right = Math.max(right, left + d.width); + top += d.height + GUI_BETWEEN; + // [ ] Verify code after upload verifyUploadBox = new JCheckBox(_("Verify code after upload")); @@ -571,6 +581,7 @@ protected void applyFrame() { // put each of the settings into the table setBoolean("build.verbose", verboseCompilationBox.isSelected()); setBoolean("upload.verbose", verboseUploadBox.isSelected()); + setBoolean("editor.linenumbers", displayLineNumbersBox.isSelected()); setBoolean("upload.verify", verifyUploadBox.isSelected()); // setBoolean("sketchbook.closing_last_window_quits", @@ -634,6 +645,7 @@ protected void showFrame(Editor editor) { // set all settings entry boxes to their actual status verboseCompilationBox.setSelected(getBoolean("build.verbose")); verboseUploadBox.setSelected(getBoolean("upload.verbose")); + displayLineNumbersBox.setSelected(getBoolean("editor.linenumbers")); verifyUploadBox.setSelected(getBoolean("upload.verify")); //closingLastQuitsBox. diff --git a/app/src/processing/app/Sketch.java b/app/src/processing/app/Sketch.java index dd3bcb2b8d4..eb974007842 100644 --- a/app/src/processing/app/Sketch.java +++ b/app/src/processing/app/Sketch.java @@ -33,16 +33,11 @@ import static processing.app.I18n._; import java.awt.*; -import java.awt.event.*; -import java.beans.*; import java.io.*; import java.util.*; import java.util.List; -import java.util.zip.*; import javax.swing.*; -import javax.swing.border.EmptyBorder; -import javax.swing.border.TitledBorder; /** @@ -2024,7 +2019,7 @@ static public String checkName(String origName) { String msg = _("The sketch name had to be modified. Sketch names can only consist\n" + "of ASCII characters and numbers (but cannot start with a number).\n" + - "They should also be less less than 64 characters long."); + "They should also be less than 64 characters long."); System.out.println(msg); } return newName; @@ -2063,9 +2058,10 @@ static public String sanitizeName(String origName) { for (int i = 0; i < c.length; i++) { if (((c[i] >= '0') && (c[i] <= '9')) || ((c[i] >= 'a') && (c[i] <= 'z')) || - ((c[i] >= 'A') && (c[i] <= 'Z'))) { + ((c[i] >= 'A') && (c[i] <= 'Z')) || + ((i > 0) && (c[i] == '-')) || + ((i > 0) && (c[i] == '.'))) { buffer.append(c[i]); - } else { buffer.append('_'); } diff --git a/app/src/processing/app/SketchCode.java b/app/src/processing/app/SketchCode.java index 807d479ea47..55b6addcaff 100644 --- a/app/src/processing/app/SketchCode.java +++ b/app/src/processing/app/SketchCode.java @@ -87,7 +87,7 @@ public SketchCode(File file, String extension) { protected void makePrettyName() { prettyName = file.getName(); - int dot = prettyName.indexOf('.'); + int dot = prettyName.lastIndexOf('.'); prettyName = prettyName.substring(0, dot); } diff --git a/app/src/processing/app/debug/AvrdudeUploader.java b/app/src/processing/app/debug/AvrdudeUploader.java index a7afb5d48cc..a9254d99a79 100755 --- a/app/src/processing/app/debug/AvrdudeUploader.java +++ b/app/src/processing/app/debug/AvrdudeUploader.java @@ -87,6 +87,7 @@ private boolean uploadViaBootloader(String buildPath, String className) // sketch. if (boardPreferences.get("bootloader.path") != null && (boardPreferences.get("bootloader.path").equals("caterina") || + boardPreferences.get("bootloader.path").equals("caterina-Arduino_Robot") || boardPreferences.get("bootloader.path").equals("caterina-LilyPadUSB"))) { String caterinaUploadPort = null; try { @@ -182,6 +183,7 @@ private boolean uploadViaBootloader(String buildPath, String className) // bootloader port. if (true == avrdudeResult && boardPreferences.get("bootloader.path") != null && (boardPreferences.get("bootloader.path").equals("caterina") || + boardPreferences.get("bootloader.path").equals("caterina-Arduino_Robot") || boardPreferences.get("bootloader.path").equals("caterina-LilyPadUSB"))) { try { Thread.sleep(500); diff --git a/app/src/processing/app/debug/Compiler.java b/app/src/processing/app/debug/Compiler.java index a715d59a408..14a7377c343 100644 --- a/app/src/processing/app/debug/Compiler.java +++ b/app/src/processing/app/debug/Compiler.java @@ -29,6 +29,7 @@ import processing.app.SketchCode; import processing.core.*; import processing.app.I18n; +import processing.app.helpers.filefilters.OnlyDirs; import static processing.app.I18n._; import java.io.*; @@ -119,8 +120,14 @@ public boolean compile(Sketch sketch, List includePaths = new ArrayList(); includePaths.add(corePath); if (variantPath != null) includePaths.add(variantPath); - for (File file : sketch.getImportedLibraries()) { - includePaths.add(file.getPath()); + for (File libFolder : sketch.getImportedLibraries()) { + // Forward compatibility with 1.5 library format + File propertiesFile = new File(libFolder, "library.properties"); + File srcFolder = new File(libFolder, "src"); + if (propertiesFile.isFile() && srcFolder.isDirectory()) + includePaths.add(srcFolder.getPath()); + else + includePaths.add(libFolder.getPath()); } // 1. compile the sketch (already in the buildPath) @@ -139,8 +146,26 @@ public boolean compile(Sketch sketch, sketch.setCompilingProgress(40); for (File libraryFolder : sketch.getImportedLibraries()) { File outputFolder = new File(buildPath, libraryFolder.getName()); - File utilityFolder = new File(libraryFolder, "utility"); createFolder(outputFolder); + + // Forward compatibility with 1.5 library format + File propertiesFile = new File(libraryFolder, "library.properties"); + File srcFolder = new File(libraryFolder, "src"); + if (propertiesFile.exists() && srcFolder.isDirectory()) { + // Is an 1.5 library with "src" folder layout + includePaths.add(srcFolder.getAbsolutePath()); + + // Recursively compile "src" folder + objectFiles.addAll(recursiveCompile(avrBasePath, srcFolder, + outputFolder, includePaths, boardPreferences)); + + includePaths.remove(includePaths.size() - 1); + continue; + } + + // Otherwise fallback to 1.0 library layout... + + File utilityFolder = new File(libraryFolder, "utility"); // this library can use includes in its utility/ folder includePaths.add(utilityFolder.getAbsolutePath()); objectFiles.addAll( @@ -251,6 +276,26 @@ public boolean compile(Sketch sketch, return true; } + private List recursiveCompile(String avrBasePath, File srcFolder, + File outputFolder, List includePaths, + Map boardPreferences) throws RunnerException { + List objectFiles = new ArrayList(); + objectFiles.addAll(compileFiles(avrBasePath, outputFolder.getAbsolutePath(), includePaths, + findFilesInFolder(srcFolder, "S", false), + findFilesInFolder(srcFolder, "c", false), + findFilesInFolder(srcFolder, "cpp", false), + boardPreferences)); + + // Recursively compile sub-folders + for (File srcSubfolder : srcFolder.listFiles(new OnlyDirs())) { + File outputSubfolder = new File(outputFolder, srcSubfolder.getName()); + createFolder(outputSubfolder); + objectFiles.addAll(recursiveCompile(avrBasePath, srcSubfolder, + outputSubfolder, includePaths, boardPreferences)); + } + + return objectFiles; + } private List compileFiles(String avrBasePath, String buildPath, List includePaths, @@ -536,6 +581,18 @@ public void message(String s) { } } + if (s.contains("undefined reference to `SPIClass::begin()'") + && s.contains("libraries/Robot_Control")) { + String error = _("Please import the SPI library from the Sketch > Import Library menu."); + exception = new RunnerException(error); + } + + if (s.contains("undefined reference to `Wire'") + && s.contains("libraries/Robot_Control")) { + String error = _("Please import the Wire library from the Sketch > Import Library menu."); + exception = new RunnerException(error); + } + System.err.print(s); } @@ -547,7 +604,7 @@ static private List getCommandCompilerS(String avrBasePath, List includePaths, avrBasePath + "avr-gcc", "-c", // compile, don't link "-g", // include debugging info (so errors include line numbers) - "-assembler-with-cpp", + "-x","assembler-with-cpp", "-mmcu=" + boardPreferences.get("build.mcu"), "-DF_CPU=" + boardPreferences.get("build.f_cpu"), "-DARDUINO=" + Base.REVISION, @@ -650,8 +707,19 @@ public boolean accept(File dir, String name) { return name.endsWith(".h"); } }; - - String[] list = (new File(path)).list(onlyHFiles); + File libFolder = new File(path); + + // Forward compatibility with 1.5 library format + File propertiesFile = new File(libFolder, "library.properties"); + File srcFolder = new File(libFolder, "src"); + String[] list; + if (propertiesFile.isFile() && srcFolder.isDirectory()) { + // Is an 1.5 library with "src" folder + list = srcFolder.list(onlyHFiles); + } else { + // Fallback to 1.0 library layout + list = libFolder.list(onlyHFiles); + } if (list == null) { throw new IOException(); } diff --git a/app/src/processing/app/helpers/FileUtils.java b/app/src/processing/app/helpers/FileUtils.java new file mode 100644 index 00000000000..47c5b0a3239 --- /dev/null +++ b/app/src/processing/app/helpers/FileUtils.java @@ -0,0 +1,93 @@ +package processing.app.helpers; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Random; + +public class FileUtils { + + /** + * Checks, whether the child directory is a subdirectory of the base directory. + * + * @param base + * the base directory. + * @param child + * the suspected child directory. + * @return true, if the child is a subdirectory of the base directory. + */ + public static boolean isSubDirectory(File base, File child) { + try { + base = base.getCanonicalFile(); + child = child.getCanonicalFile(); + } catch (IOException e) { + return false; + } + + File parentFile = child; + while (parentFile != null) { + if (base.equals(parentFile)) { + return true; + } + parentFile = parentFile.getParentFile(); + } + return false; + } + + public static void copy(File sourceFolder, File destFolder) throws IOException { + for (File file : sourceFolder.listFiles()) { + File destFile = new File(destFolder, file.getName()); + if (file.isDirectory()) { + if (!destFile.mkdir()) { + throw new IOException("Unable to create folder: " + destFile); + } + copy(file, destFile); + } else { + FileInputStream fis = null; + FileOutputStream fos = null; + try { + fis = new FileInputStream(file); + fos = new FileOutputStream(destFile); + byte[] buf = new byte[4096]; + int readBytes = -1; + while ((readBytes = fis.read(buf, 0, buf.length)) != -1) { + fos.write(buf, 0, readBytes); + } + } finally { + if (fis != null) { + fis.close(); + } + if (fos != null) { + fos.close(); + } + } + } + } + } + + public static void recursiveDelete(File file) { + if (file == null) { + return; + } + if (file.isDirectory()) { + for (File current : file.listFiles()) { + if (current.isDirectory()) { + recursiveDelete(current); + } else { + current.delete(); + } + } + } + file.delete(); + } + + public static File createTempFolder() throws IOException { + File tmpFolder = new File(System.getProperty("java.io.tmpdir"), "arduino_" + new Random().nextInt(1000000)); + if (!tmpFolder.mkdir()) { + throw new IOException("Unable to create temp folder " + tmpFolder); + } + return tmpFolder; + } + +} diff --git a/app/src/processing/app/helpers/filefilters/OnlyDirs.java b/app/src/processing/app/helpers/filefilters/OnlyDirs.java new file mode 100644 index 00000000000..46f407248d1 --- /dev/null +++ b/app/src/processing/app/helpers/filefilters/OnlyDirs.java @@ -0,0 +1,42 @@ +/* + OnlyDirs - FilenameFilter that accepts only directories (CVS, .svn, + .DS_Store files are excluded as well) + Part of the Arduino project - http://www.arduino.cc/ + + Copyright (c) 2011 Cristian Maglie + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +package processing.app.helpers.filefilters; + +import java.io.File; +import java.io.FilenameFilter; + +/** + * This filter accepts only directories (excluding .DS_Store files, .svn + * folders, etc) + * + * @author Cristian Maglie + */ +public class OnlyDirs implements FilenameFilter { + + public boolean accept(File dir, String name) { + if (name.charAt(0) == '.') + return false; + if (name.equals("CVS")) + return false; + return new File(dir, name).isDirectory(); + } +} diff --git a/app/src/processing/app/javax/swing/filechooser/FileNameExtensionFilter.java b/app/src/processing/app/javax/swing/filechooser/FileNameExtensionFilter.java new file mode 100644 index 00000000000..a0ef013188b --- /dev/null +++ b/app/src/processing/app/javax/swing/filechooser/FileNameExtensionFilter.java @@ -0,0 +1,48 @@ +package processing.app.javax.swing.filechooser; + +import javax.swing.filechooser.FileFilter; +import java.io.File; +import java.util.Locale; + +public class FileNameExtensionFilter extends FileFilter { + + private final String description; + private final String[] extensions; + + public FileNameExtensionFilter(String description, String... exts) { + this.description = description; + this.extensions = new String[exts.length]; + for (int i = 0; i < exts.length; i++) { + this.extensions[i] = exts[i].toLowerCase(Locale.ENGLISH); + } + } + + @Override + public boolean accept(File f) { + if (f == null) { + return false; + } + + if (f.isDirectory()) { + return true; + } + + String fileName = f.getName(); + int i = fileName.lastIndexOf('.'); + if (i > 0 && i < fileName.length() - 1) { + String fileExtension = fileName.substring(i + 1).toLowerCase(Locale.ENGLISH); + for (String extension : extensions) { + if (extension.equals(fileExtension)) { + return true; + } + } + } + + return false; + } + + @Override + public String getDescription() { + return description; + } +} diff --git a/app/src/processing/app/syntax/JEditTextArea.java b/app/src/processing/app/syntax/JEditTextArea.java index fae0698cc5c..07628e85e4f 100644 --- a/app/src/processing/app/syntax/JEditTextArea.java +++ b/app/src/processing/app/syntax/JEditTextArea.java @@ -87,6 +87,7 @@ public JEditTextArea(TextAreaDefaults defaults) // Initialize some misc. stuff painter = new TextAreaPainter(this,defaults); + editorLineNumbers = new TextAreaLineNumbers(this,defaults); documentHandler = new DocumentHandler(); eventListenerList = new EventListenerList(); caretEvent = new MutableCaretEvent(); @@ -96,6 +97,7 @@ public JEditTextArea(TextAreaDefaults defaults) // Initialize the GUI setLayout(new ScrollLayout()); + add(LEFT, editorLineNumbers); add(CENTER, painter); add(RIGHT, vertical = new JScrollBar(JScrollBar.VERTICAL)); add(BOTTOM, horizontal = new JScrollBar(JScrollBar.HORIZONTAL)); @@ -315,6 +317,14 @@ public void updateScrollBars() { horizontal.setUnitIncrement(charWidth); horizontal.setBlockIncrement(width / 2); } + updateLineNumbers(); + } + + private void updateLineNumbers() { + if (editorLineNumbers != null) { + editorLineNumbers.updateLineNumbers(getFirstLine() + 1, Math.min(getFirstLine() + getVisibleLines() + 1, getLineCount())); + editorLineNumbers.updateWidthForNumDigits(String.valueOf(getLineCount()).length()); + } } /** @@ -335,7 +345,7 @@ public void setFirstLine(int firstLine) { if (firstLine != vertical.getValue()) { updateScrollBars(); } - painter.repaint(); + repaintEditor(); } /** @@ -377,7 +387,7 @@ public void setHorizontalOffset(int horizontalOffset) this.horizontalOffset = horizontalOffset; if(horizontalOffset != horizontal.getValue()) updateScrollBars(); - painter.repaint(); + repaintEditor(); } /** @@ -407,12 +417,17 @@ public boolean setOrigin(int firstLine, int horizontalOffset) if(changed) { updateScrollBars(); - painter.repaint(); + repaintEditor(); } return changed; } + private void repaintEditor() { + painter.repaint(); + updateLineNumbers(); + } + /** * Ensures that the caret is visible by scrolling the text area if * necessary. @@ -732,7 +747,7 @@ public void setDocument(SyntaxDocument document) { select(0, 0); updateScrollBars(); - painter.repaint(); + repaintEditor(); } @@ -753,7 +768,7 @@ public void setDocument(SyntaxDocument document, select(start, stop); updateScrollBars(); setScrollPosition(scroll); - painter.repaint(); + repaintEditor(); } @@ -790,7 +805,11 @@ public final int getDocumentLength() */ public final int getLineCount() { - return document.getDefaultRootElement().getElementCount(); + if (document != null) { + return document.getDefaultRootElement().getElementCount(); + } else { + return 0; + } } /** @@ -1187,6 +1206,16 @@ public void select(int start, int end) selectionEndLine = newEndLine; biasLeft = newBias; + if (newStart != newEnd) { + Clipboard unixclipboard = getToolkit().getSystemSelection(); + if (unixclipboard != null) { + String selection = getSelectedText(); + if (selection != null) { + unixclipboard.setContents(new StringSelection(selection), null); + } + } + } + fireCaretEvent(); } @@ -1649,7 +1678,11 @@ public void copy() for(int i = 0; i < repeatCount; i++) buf.append(selection); - clipboard.setContents(new StringSelection(buf.toString()),null); + Transferable t = new StringSelection(buf.toString()); + clipboard.setContents(t, null); + + Clipboard unixclipboard = getToolkit().getSystemSelection(); + if (unixclipboard != null) unixclipboard.setContents(t, null); } } @@ -1733,6 +1766,7 @@ public void processKeyEvent(KeyEvent evt) { } // protected members + protected static String LEFT = "left"; protected static String CENTER = "center"; protected static String RIGHT = "right"; protected static String BOTTOM = "bottom"; @@ -1741,6 +1775,7 @@ public void processKeyEvent(KeyEvent evt) { protected static Timer caretTimer; protected TextAreaPainter painter; + protected TextAreaLineNumbers editorLineNumbers; //protected EditPopupMenu popup; protected JPopupMenu popup; @@ -1867,7 +1902,9 @@ class ScrollLayout implements LayoutManager public void addLayoutComponent(String name, Component comp) { - if(name.equals(CENTER)) + if(name.equals(LEFT)) + left = comp; + else if(name.equals(CENTER)) center = comp; else if(name.equals(RIGHT)) right = comp; @@ -1879,6 +1916,8 @@ else if(name.equals(LEFT_OF_SCROLLBAR)) public void removeLayoutComponent(Component comp) { + if(left == comp) + left = null; if(center == comp) center = null; if(right == comp) @@ -1899,6 +1938,8 @@ public Dimension preferredLayoutSize(Container parent) Dimension centerPref = center.getPreferredSize(); dim.width += centerPref.width; dim.height += centerPref.height; + Dimension leftPref = left.getPreferredSize(); + dim.width += leftPref.width; Dimension rightPref = right.getPreferredSize(); dim.width += rightPref.width; Dimension bottomPref = bottom.getPreferredSize(); @@ -1917,6 +1958,8 @@ public Dimension minimumLayoutSize(Container parent) Dimension centerPref = center.getMinimumSize(); dim.width += centerPref.width; dim.height += centerPref.height; + Dimension leftPref = left.getMinimumSize(); + dim.width += leftPref.width; Dimension rightPref = right.getMinimumSize(); dim.width += rightPref.width; Dimension bottomPref = bottom.getMinimumSize(); @@ -1936,11 +1979,19 @@ public void layoutContainer(Container parent) int ibottom = insets.bottom; int iright = insets.right; + int leftWidth = left.getSize().width; int rightWidth = right.getPreferredSize().width; int bottomHeight = bottom.getPreferredSize().height; - int centerWidth = size.width - rightWidth - ileft - iright; + int centerWidth = size.width - leftWidth - rightWidth - ileft - iright; int centerHeight = size.height - bottomHeight - itop - ibottom; + left.setBounds(ileft, + itop, + leftWidth, + centerHeight); + + ileft += leftWidth; + center.setBounds(ileft, // + LEFT_EXTRA, itop, centerWidth, // - LEFT_EXTRA, @@ -1970,6 +2021,7 @@ public void layoutContainer(Container parent) } // private members + private Component left; private Component center; private Component right; private Component bottom; @@ -2206,6 +2258,25 @@ public void mousePressed(MouseEvent evt) return; } + // on Linux, middle button pastes selected text + if ((evt.getModifiers() & InputEvent.BUTTON2_MASK) != 0) { + Clipboard unixclipboard = getToolkit().getSystemSelection(); + if (unixclipboard != null) { + Transferable t = unixclipboard.getContents(null); + if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) { + try { + String s = (String)t.getTransferData(DataFlavor.stringFlavor); + s = s.replace('\u00A0', ' '); + if (editable) setSelectedText(s); + } catch (Exception e) { + System.err.println(e); + e.printStackTrace(); + } + } + return; + } + } + int line = yToLine(evt.getY()); int offset = xToOffset(line,evt.getX()); int dot = getLineStartOffset(line) + offset; @@ -2362,4 +2433,8 @@ public boolean addEdit(UndoableEdit edit) caretTimer.setInitialDelay(500); caretTimer.start(); } + + public void setDisplayLineNumbers(boolean displayLineNumbers) { + editorLineNumbers.setDisplayLineNumbers(displayLineNumbers); + } } diff --git a/app/src/processing/app/syntax/TextAreaLineNumbers.java b/app/src/processing/app/syntax/TextAreaLineNumbers.java new file mode 100644 index 00000000000..39f7438f281 --- /dev/null +++ b/app/src/processing/app/syntax/TextAreaLineNumbers.java @@ -0,0 +1,106 @@ +/* + * TextAreaLineNumbers.java - Show line numbers for the open file in the editor + * Copyright (C) 2013 Cayci Gorlitsky + * + * You may use and modify this package for any purpose. Redistribution is + * permitted, in both source and binary form, provided that this notice + * remains intact in all source distributions of this package. + */ + +package processing.app.syntax; + +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Rectangle; + +import javax.swing.border.MatteBorder; + +public class TextAreaLineNumbers extends TextAreaPainter { + + private final int LEFT_INDENT = 6; + private final int RIGHT_INDENT = 6; + private final int RIGHT_BORDER_WIDTH = 1; + private final int PADDING_WIDTH = LEFT_INDENT + RIGHT_INDENT + RIGHT_BORDER_WIDTH; + + private final int MIN_WIDTH; + private final int DIGIT_WIDTH; + private final int MIN_NUM_DIGITS = 2; + + private int currStartNum = 0; + private int currEndNum = 0; + private int currNumDigits = MIN_NUM_DIGITS; + + + + public TextAreaLineNumbers(JEditTextArea textArea, TextAreaDefaults defaults) { + super(textArea, defaults); + DIGIT_WIDTH = getFontMetrics(getFont()).stringWidth("0"); + MIN_WIDTH = DIGIT_WIDTH * MIN_NUM_DIGITS + PADDING_WIDTH; + setEnabled(false); + setBorder(new MatteBorder(0, 0, 0, RIGHT_BORDER_WIDTH, new Color(240, 240, 240))); + } + + public void updateLineNumbers(int startNum, int endNum) { + if (currStartNum == startNum && currEndNum == endNum) { + return; + } + currStartNum = startNum; + currEndNum = endNum; + + invalidate(); + repaint(); + } + + @Override + public void paint(Graphics gfx) { + super.paint(gfx); + getBorder().paintBorder(this, gfx, 0, 0, getSize().width, getSize().height); + } + + @Override + protected void paintLine(Graphics gfx, TokenMarker tokenMarker, + int line, int x) + { + currentLineIndex = line; + gfx.setFont(getFont()); + gfx.setColor(Color.GRAY); + int y = textArea.lineToY(line); + int startX = getBounds().x + getBounds().width; + if (line >= 0 && line < textArea.getLineCount()) { + String lineNumberString = String.valueOf(line+1); + int lineStartX = startX - RIGHT_BORDER_WIDTH - RIGHT_INDENT - fm.stringWidth(lineNumberString); + gfx.drawString(lineNumberString,lineStartX,y + fm.getHeight()); + } + } + + public void updateWidthForNumDigits(int numDigits) { + if (currNumDigits == numDigits) { + return; + } + currNumDigits = numDigits; + + if (isVisible()) { + updateBounds(); + invalidate(); + repaint(); + } + } + + public void setDisplayLineNumbers(boolean displayLineNumbers) { + setVisible(displayLineNumbers); + if (displayLineNumbers) { + updateBounds(); + } else { + setBounds(new Rectangle(0, getHeight())); + } + invalidate(); + repaint(); + } + + private void updateBounds() { + if (isVisible()) { + setBounds(new Rectangle(Math.max(MIN_WIDTH, DIGIT_WIDTH * currNumDigits + PADDING_WIDTH), getHeight())); + textArea.validate(); + } + } +} diff --git a/app/src/processing/app/tools/DiscourseFormat.java b/app/src/processing/app/tools/DiscourseFormat.java index 097d7ee2cc3..5494a9ca3cb 100644 --- a/app/src/processing/app/tools/DiscourseFormat.java +++ b/app/src/processing/app/tools/DiscourseFormat.java @@ -108,6 +108,8 @@ public void lostOwnership(Clipboard clipboard, Transferable contents) { // i don't care about ownership } }); + Clipboard unixclipboard = Toolkit.getDefaultToolkit().getSystemSelection(); + if (unixclipboard != null) unixclipboard.setContents(formatted, null); editor.statusNotice("Code formatted for " + (html ? "HTML" : "the Arduino forum ") + diff --git a/app/src/processing/app/tools/ZipDeflater.java b/app/src/processing/app/tools/ZipDeflater.java index 651ff37ba30..55f0c0c8b8c 100644 --- a/app/src/processing/app/tools/ZipDeflater.java +++ b/app/src/processing/app/tools/ZipDeflater.java @@ -10,30 +10,36 @@ import java.util.zip.ZipException; import java.util.zip.ZipFile; +import processing.app.helpers.FileUtils; + public class ZipDeflater { private final ZipFile zipFile; private final File destFolder; + private final Random random; + private final File file; public ZipDeflater(File file, File destFolder) throws ZipException, IOException { + this.file = file; this.destFolder = destFolder; this.zipFile = new ZipFile(file); + this.random = new Random(); } public void deflate() throws IOException { - String folderName = tempFolderNameFromZip(); + String tmpFolderName = folderNameFromZip() + random.nextInt(1000000); - File folder = new File(destFolder, folderName); + File tmpFolder = new File(destFolder, tmpFolderName); - if (!folder.mkdir()) { - throw new IOException("Unable to create folder " + folderName); + if (!tmpFolder.mkdir()) { + throw new IOException("Unable to create folder " + tmpFolderName); } Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); - ensureFoldersOfEntryExist(folder, entry); - File entryFile = new File(folder, entry.getName()); + ensureFoldersOfEntryExist(tmpFolder, entry); + File entryFile = new File(tmpFolder, entry.getName()); if (entry.isDirectory()) { entryFile.mkdir(); } else { @@ -58,8 +64,20 @@ public void deflate() throws IOException { } } - // Test.zip may or may not contain Test folder. We use zip name to create libraries folder. Therefore, a contained Test folder is useless and must be removed - ensureOneLevelFolder(folder); + deleteUndesiredFoldersAndFiles(tmpFolder); + + // Test.zip may or may not contain Test folder. If it does, we keep it. If not, we use zip name. + ensureOneLevelFolder(tmpFolder); + } + + private void deleteUndesiredFoldersAndFiles(File folder) { + for (File file : folder.listFiles()) { + if (file.isDirectory() && "__MACOSX".equals(file.getName())) { + FileUtils.recursiveDelete(file); + } else if (file.getName().startsWith(".")) { + FileUtils.recursiveDelete(file); + } + } } private void ensureFoldersOfEntryExist(File folder, ZipEntry entry) { @@ -73,25 +91,22 @@ private void ensureFoldersOfEntryExist(File folder, ZipEntry entry) { private void ensureOneLevelFolder(File folder) { File[] files = folder.listFiles(); - if (files.length == 1 && files[0].isDirectory()) { - File tempFile = new File(files[0].getPath() + new Random().nextInt(1000)); - files[0].renameTo(tempFile); - for (File file : tempFile.listFiles()) { - file.renameTo(new File(folder, file.getName())); - } - tempFile.delete(); + + if (files.length != 1) { + folder.renameTo(new File(folder.getParentFile(), folderNameFromZip())); + return; } + + files[0].renameTo(new File(folder.getParentFile(), files[0].getName())); + FileUtils.recursiveDelete(folder); } - private String tempFolderNameFromZip() { - String folderName = zipFile.getName(); - if (folderName.lastIndexOf(".") != -1) { - folderName = folderName.substring(0, folderName.lastIndexOf(".")); - } - if (folderName.lastIndexOf(File.separator) != -1) { - folderName = folderName.substring(folderName.lastIndexOf(File.separator) + 1); + private String folderNameFromZip() { + String filename = file.getName(); + if (filename.lastIndexOf(".") != -1) { + filename = filename.substring(0, filename.lastIndexOf(".")); } - return folderName; + return filename; } } diff --git a/build/build.xml b/build/build.xml index 91d562346cd..b1b3fbbed90 100644 --- a/build/build.xml +++ b/build/build.xml @@ -20,6 +20,9 @@ + + + @@ -457,8 +460,22 @@ - - + + + + + + + + + + + + + + @@ -492,19 +509,22 @@ - + + + - + - + + diff --git a/build/shared/examples/01.Basics/Blink/Blink.ino b/build/shared/examples/01.Basics/Blink/Blink.ino index 15b9911407d..b0db92b8665 100644 --- a/build/shared/examples/01.Basics/Blink/Blink.ino +++ b/build/shared/examples/01.Basics/Blink/Blink.ino @@ -1,24 +1,29 @@ /* Blink Turns on an LED on for one second, then off for one second, repeatedly. - + + Most Arduinos have an on-board LED you can control. On the Uno and + Leonardo, it is attached to digital pin 13. If you're unsure what + pin the on-board LED is connected to on your Arduino model, check + the documentation at http://arduino.cc + This example code is in the public domain. + + modified 8 May 2014 + by Scott Fitzgerald */ - -// Pin 13 has an LED connected on most Arduino boards. -// give it a name: -int led = 13; -// the setup routine runs once when you press reset: -void setup() { - // initialize the digital pin as an output. - pinMode(led, OUTPUT); + +// the setup function runs once when you press reset or power the board +void setup() { + // initialize digital pin 13 as an output. + pinMode(13, OUTPUT); } -// the loop routine runs over and over again forever: +// the loop function runs over and over again forever void loop() { - digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level) - delay(1000); // wait for a second - digitalWrite(led, LOW); // turn the LED off by making the voltage LOW - delay(1000); // wait for a second + digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level) + delay(1000); // wait for a second + digitalWrite(13, LOW); // turn the LED off by making the voltage LOW + delay(1000); // wait for a second } diff --git a/build/shared/examples/02.Digital/BlinkWithoutDelay/BlinkWithoutDelay.ino b/build/shared/examples/02.Digital/BlinkWithoutDelay/BlinkWithoutDelay.ino index 014357191d0..56b274efcb0 100644 --- a/build/shared/examples/02.Digital/BlinkWithoutDelay/BlinkWithoutDelay.ino +++ b/build/shared/examples/02.Digital/BlinkWithoutDelay/BlinkWithoutDelay.ino @@ -9,29 +9,31 @@ * Note: on most Arduinos, there is already an LED on the board that's attached to pin 13, so no hardware is needed for this example. - created 2005 by David A. Mellis modified 8 Feb 2010 by Paul Stoffregen + modified 11 Nov 2013 + by Scott Fitzgerald + This example code is in the public domain. - http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay */ -// constants won't change. Used here to -// set pin numbers: +// constants won't change. Used here to set a pin number : const int ledPin = 13; // the number of the LED pin -// Variables will change: +// Variables will change : int ledState = LOW; // ledState used to set the LED -long previousMillis = 0; // will store last time LED was updated -// the follow variables is a long because the time, measured in miliseconds, -// will quickly become a bigger number than can be stored in an int. -long interval = 1000; // interval at which to blink (milliseconds) +// Generally, you shuould use "unsigned long" for variables that hold time +// The value will quickly become too large for an int to store +unsigned long previousMillis = 0; // will store last time LED was updated + +// constants won't change : +const long interval = 1000; // interval at which to blink (milliseconds) void setup() { // set the digital pin as output: @@ -48,7 +50,7 @@ void loop() // blink the LED. unsigned long currentMillis = millis(); - if(currentMillis - previousMillis > interval) { + if(currentMillis - previousMillis >= interval) { // save the last time you blinked the LED previousMillis = currentMillis; diff --git a/build/shared/examples/02.Digital/Debounce/Debounce.ino b/build/shared/examples/02.Digital/Debounce/Debounce.ino index 89416b26921..da3aa29d9e0 100644 --- a/build/shared/examples/02.Digital/Debounce/Debounce.ino +++ b/build/shared/examples/02.Digital/Debounce/Debounce.ino @@ -19,16 +19,18 @@ by David A. Mellis modified 30 Aug 2011 by Limor Fried + modified 28 Dec 2012 + by Mike Walters -This example code is in the public domain. + This example code is in the public domain. http://www.arduino.cc/en/Tutorial/Debounce */ // constants won't change. They're used here to // set pin numbers: -const int buttonPin = 2; // the number of the pushbutton pin -const int ledPin = 13; // the number of the LED pin +const int buttonPin = 2; // the number of the pushbutton pin +const int ledPin = 13; // the number of the LED pin // Variables will change: int ledState = HIGH; // the current state of the output pin @@ -43,6 +45,9 @@ long debounceDelay = 50; // the debounce time; increase if the output flicker void setup() { pinMode(buttonPin, INPUT); pinMode(ledPin, OUTPUT); + + // set initial LED state + digitalWrite(ledPin, ledState); } void loop() { @@ -62,11 +67,20 @@ void loop() { if ((millis() - lastDebounceTime) > debounceDelay) { // whatever the reading is at, it's been there for longer // than the debounce delay, so take it as the actual current state: - buttonState = reading; + + // if the button state has changed: + if (reading != buttonState) { + buttonState = reading; + + // only toggle the LED if the new button state is HIGH + if (buttonState == HIGH) { + ledState = !ledState; + } + } } - // set the LED using the state of the button: - digitalWrite(ledPin, buttonState); + // set the LED: + digitalWrite(ledPin, ledState); // save the reading. Next time through the loop, // it'll be the lastButtonState: diff --git a/build/shared/examples/02.Digital/toneMultiple/toneMultiple.ino b/build/shared/examples/02.Digital/toneMultiple/toneMultiple.ino index 52a06df5217..1a92e7fccc4 100644 --- a/build/shared/examples/02.Digital/toneMultiple/toneMultiple.ino +++ b/build/shared/examples/02.Digital/toneMultiple/toneMultiple.ino @@ -4,7 +4,7 @@ Plays multiple tones on multiple pins in sequence circuit: - * 3 8-ohm speaker on digital pins 6, 7, and 11 + * 3 8-ohm speaker on digital pins 6, 7, and 8 created 8 March 2010 by Tom Igoe @@ -21,8 +21,8 @@ void setup() { } void loop() { - // turn off tone function for pin 11: - noTone(11); + // turn off tone function for pin 8: + noTone(8); // play a note on pin 6 for 200 ms: tone(6, 440, 200); delay(200); @@ -35,8 +35,7 @@ void loop() { // turn off tone function for pin 7: noTone(7); - // play a note on pin 11 for 500 ms: - tone(11, 523, 300); + // play a note on pin 8 for 500 ms: + tone(8, 523, 300); delay(300); - } diff --git a/build/shared/examples/02.Digital/tonePitchFollower/tonePitchFollower.ino b/build/shared/examples/02.Digital/tonePitchFollower/tonePitchFollower.ino index e74c7b34344..69caff744ff 100644 --- a/build/shared/examples/02.Digital/tonePitchFollower/tonePitchFollower.ino +++ b/build/shared/examples/02.Digital/tonePitchFollower/tonePitchFollower.ino @@ -4,7 +4,7 @@ Plays a pitch that changes based on a changing analog input circuit: - * 8-ohm speaker on digital pin 8 + * 8-ohm speaker on digital pin 9 * photoresistor on analog 0 to 5V * 4.7K resistor on analog 0 to ground diff --git a/build/shared/examples/04.Communication/Dimmer/Dimmer.ino b/build/shared/examples/04.Communication/Dimmer/Dimmer.ino index 78849c2c991..bbd27a8e508 100644 --- a/build/shared/examples/04.Communication/Dimmer/Dimmer.ino +++ b/build/shared/examples/04.Communication/Dimmer/Dimmer.ino @@ -55,6 +55,7 @@ void loop() { size(256, 150); println("Available serial ports:"); + // if using Processing 2.1 or later, use Serial.printArray() println(Serial.list()); // Uses the first port in this list (number 0). Change this to diff --git a/build/shared/examples/04.Communication/Graph/Graph.ino b/build/shared/examples/04.Communication/Graph/Graph.ino index c2e4637b6a9..58c89994fb4 100644 --- a/build/shared/examples/04.Communication/Graph/Graph.ino +++ b/build/shared/examples/04.Communication/Graph/Graph.ino @@ -63,13 +63,17 @@ void loop() { size(400, 300); // List all the available serial ports + // if using Processing 2.1 or later, use Serial.printArray() println(Serial.list()); + // I know that the first port in the serial list on my mac // is always my Arduino, so I open Serial.list()[0]. // Open whatever port is the one you're using. myPort = new Serial(this, Serial.list()[0], 9600); + // don't generate a serialEvent() unless you get a newline character: myPort.bufferUntil('\n'); + // set inital background: background(0); } diff --git a/build/shared/examples/04.Communication/PhysicalPixel/PhysicalPixel.ino b/build/shared/examples/04.Communication/PhysicalPixel/PhysicalPixel.ino index 7ac8231a679..6204e09fef6 100644 --- a/build/shared/examples/04.Communication/PhysicalPixel/PhysicalPixel.ino +++ b/build/shared/examples/04.Communication/PhysicalPixel/PhysicalPixel.ino @@ -84,6 +84,7 @@ void loop() { // You will need to choose the port that the Arduino board is // connected to from this list. The first port in the list is // port #0 and the third port in the list is port #2. + // if using Processing 2.1 or later, use Serial.printArray() println(Serial.list()); // Open the port that the Arduino board is connected to (in this case #0) diff --git a/build/shared/examples/04.Communication/SerialCallResponse/SerialCallResponse.ino b/build/shared/examples/04.Communication/SerialCallResponse/SerialCallResponse.ino index dc004c9b20d..11691ef8be7 100644 --- a/build/shared/examples/04.Communication/SerialCallResponse/SerialCallResponse.ino +++ b/build/shared/examples/04.Communication/SerialCallResponse/SerialCallResponse.ino @@ -92,7 +92,8 @@ void setup() { xpos = width/2; ypos = height/2; - // Print a list of the serial ports, for debugging purposes: + // Print a list of the serial ports for debugging purposes + // if using Processing 2.1 or later, use Serial.printArray() println(Serial.list()); // I know that the first port in the serial list on my mac diff --git a/build/shared/examples/04.Communication/SerialCallResponseASCII/SerialCallResponseASCII.ino b/build/shared/examples/04.Communication/SerialCallResponseASCII/SerialCallResponseASCII.ino index 3c6f94ed2b4..d8c94956f8c 100644 --- a/build/shared/examples/04.Communication/SerialCallResponseASCII/SerialCallResponseASCII.ino +++ b/build/shared/examples/04.Communication/SerialCallResponseASCII/SerialCallResponseASCII.ino @@ -91,6 +91,7 @@ void setup() { size(640,480); // List all the available serial ports + // if using Processing 2.1 or later, use Serial.printArray() println(Serial.list()); // I know that the first port in the serial list on my mac diff --git a/build/shared/examples/04.Communication/VirtualColorMixer/VirtualColorMixer.ino b/build/shared/examples/04.Communication/VirtualColorMixer/VirtualColorMixer.ino index 39e4b57619a..6a2cd19089f 100644 --- a/build/shared/examples/04.Communication/VirtualColorMixer/VirtualColorMixer.ino +++ b/build/shared/examples/04.Communication/VirtualColorMixer/VirtualColorMixer.ino @@ -50,7 +50,9 @@ void loop() size(200, 200); // List all the available serial ports + // if using Processing 2.1 or later, use Serial.printArray() println(Serial.list()); + // I know that the first port in the serial list on my mac // is always my Arduino, so I open Serial.list()[0]. // Open whatever port is the one you're using. diff --git a/build/shared/examples/08.Strings/StringStartsWithEndsWith/StringStartsWithEndsWith.ino b/build/shared/examples/08.Strings/StringStartsWithEndsWith/StringStartsWithEndsWith.ino index b2509e56d8e..41640cbf4ef 100644 --- a/build/shared/examples/08.Strings/StringStartsWithEndsWith/StringStartsWithEndsWith.ino +++ b/build/shared/examples/08.Strings/StringStartsWithEndsWith/StringStartsWithEndsWith.ino @@ -42,12 +42,11 @@ void loop() { String sensorReading = "sensor = "; sensorReading += analogRead(A0); Serial.print (sensorReading); - if (sensorReading.endsWith(0)) { + if (sensorReading.endsWith("0")) { Serial.println(". This reading is divisible by ten"); } else { Serial.println(". This reading is not divisible by ten"); - } // do nothing while true: diff --git a/build/shared/examples/09.USB/Keyboard/KeyboardMessage/KeyboardMessage.ino b/build/shared/examples/09.USB/Keyboard/KeyboardMessage/KeyboardMessage.ino index 35d06c6a30e..1f17668d131 100644 --- a/build/shared/examples/09.USB/Keyboard/KeyboardMessage/KeyboardMessage.ino +++ b/build/shared/examples/09.USB/Keyboard/KeyboardMessage/KeyboardMessage.ino @@ -1,24 +1,26 @@ /* - Keyboard Button test + Keyboard Message test For the Arduino Leonardo and Micro. Sends a text string when a button is pressed. The circuit: - * pushbutton attached from pin 2 to +5V + * pushbutton attached from pin 4 to +5V * 10-kilohm resistor attached from pin 4 to ground created 24 Oct 2011 modified 27 Mar 2012 by Tom Igoe + modified 11 Nov 2013 + by Scott Fitzgerald This example code is in the public domain. - http://www.arduino.cc/en/Tutorial/KeyboardButton + http://www.arduino.cc/en/Tutorial/KeyboardMessage */ -const int buttonPin = 2; // input pin for pushbutton +const int buttonPin = 4; // input pin for pushbutton int previousButtonState = HIGH; // for checking the state of a pushButton int counter = 0; // button push counter diff --git a/build/shared/examples/09.USB/Keyboard/KeyboardReprogram/KeyboardReprogram.ino b/build/shared/examples/09.USB/Keyboard/KeyboardReprogram/KeyboardReprogram.ino index 17cb04d7b3c..08e47479b0c 100644 --- a/build/shared/examples/09.USB/Keyboard/KeyboardReprogram/KeyboardReprogram.ino +++ b/build/shared/examples/09.USB/Keyboard/KeyboardReprogram/KeyboardReprogram.ino @@ -11,12 +11,14 @@ a final key combination (CTRL-U). Circuit: - * Arduino Leonardo or Micro + * Arduino Leonardo, Micro, Due, LilyPad USB, or Yun * wire to connect D2 to ground. created 5 Mar 2012 modified 29 Mar 2012 by Tom Igoe + modified 3 May 2014 + by Scott Fitzgerald This example is in the public domain @@ -54,6 +56,18 @@ void loop() { // wait for new window to open: delay(1000); + // versions of the Arduino IDE after 1.5 pre-populate + // new sketches with setup() and loop() functions + // let's clear the window before typing anything new + // select all + Keyboard.press(ctrlKey); + Keyboard.press('a'); + delay(500); + Keyboard.releaseAll(); + // delete the selected text + Keyboard.write(KEY_BACKSPACE); + delay(500); + // Type out "blink": Keyboard.println("void setup() {"); Keyboard.println("pinMode(13, OUTPUT);"); @@ -93,3 +107,4 @@ void loop() { + diff --git a/build/shared/examples/10.StarterKit/p02_SpaceshipInterface/p02_SpaceshipInterface.ino b/build/shared/examples/10.StarterKit/p02_SpaceshipInterface/p02_SpaceshipInterface.ino index 84893529a1e..2a14276375c 100644 --- a/build/shared/examples/10.StarterKit/p02_SpaceshipInterface/p02_SpaceshipInterface.ino +++ b/build/shared/examples/10.StarterKit/p02_SpaceshipInterface/p02_SpaceshipInterface.ino @@ -44,7 +44,7 @@ void loop(){ switchstate = digitalRead(2); // if the button is not pressed - // blink the red LEDs + // turn on the green LED and off the red LEDs if (switchstate == LOW) { digitalWrite(3, HIGH); // turn the green LED on pin 3 on digitalWrite(4, LOW); // turn the red LED on pin 4 off @@ -52,7 +52,7 @@ void loop(){ } // this else is part of the above if() statement. // if the switch is not LOW (the button is pressed) - // the code below will run + // turn off the green LED and blink alternatively the red LEDs else { digitalWrite(3, LOW); // turn the green LED on pin 3 off digitalWrite(4, LOW); // turn the red LED on pin 4 off diff --git a/build/shared/lib/arduino_icon.ico b/build/shared/lib/arduino_icon.ico new file mode 100755 index 00000000000..a9f3a7acbe5 Binary files /dev/null and b/build/shared/lib/arduino_icon.ico differ diff --git a/build/shared/lib/keywords.txt b/build/shared/lib/keywords.txt index ac7de85f803..422b39cda37 100644 --- a/build/shared/lib/keywords.txt +++ b/build/shared/lib/keywords.txt @@ -182,6 +182,8 @@ parseInt KEYWORD2 parseFloat KEYWORD2 readBytes KEYWORD2 readBytesUntil KEYWORD2 +readString KEYWORD2 +readStringUntil KEYWORD2 # USB-related keywords diff --git a/build/shared/lib/preferences.txt b/build/shared/lib/preferences.txt index 67246f860e7..f9bac321b33 100755 --- a/build/shared/lib/preferences.txt +++ b/build/shared/lib/preferences.txt @@ -104,6 +104,9 @@ editor.caret.blink=true # area that's not in use by the text (replaced with tildes) editor.invalid=false +# show line numbers in editor +editor.linenumbers = false + # enable ctrl-ins, shift-ins, shift-delete for cut/copy/paste # on windows and linux, but disable on the mac editor.keys.alternative_cut_copy_paste = true diff --git a/build/shared/revisions.txt b/build/shared/revisions.txt index 4fd13559211..c0bc7ca95dc 100644 --- a/build/shared/revisions.txt +++ b/build/shared/revisions.txt @@ -1,15 +1,26 @@ -ARDUINO 1.0.5 - 2013.04.08 +ARDUINO 1.0.5-r2 - 2014.01.08 + +* Signed drivers for Windows 8.1 +* Fixed Windows drivers signature (that prevented installation on + some Windows 8.x OS). Now the signature is timestamped and should + not expire. + +ARDUINO 1.0.5 - 2013.05.15 [core] * [avr] malloc bug: backported avr-libc 1.8.0 implementation * [avr] removed deprecated interrupt handlers causing compiler issues with newer avr-gcc. +* [avr] added c_str() method to String +* [avr] Stream "_timeout" field and related methods are now protected [libraries] * Upgrades to WiFi library +* Fixed a bunch of examples +* Added Arduino Robot libraries [firmwares] @@ -17,13 +28,16 @@ ARDUINO 1.0.5 - 2013.04.08 [ide] -* Backport from 1.5: install Library from file +* Backport from 1.5: install Library from .zip file or folder +* Updated windows drivers +* Added Windows installer ARDUINO 1.0.4 - 2013.03.11 [core] * Fixed malloc bug (Paul Stoffregen) +* Added INT6 support for Leonardo (Federico Vanzati) [libraries] diff --git a/build/windows/dist/drivers/arduino.cat b/build/windows/dist/drivers/arduino.cat index 45d2c220739..228c7104ff5 100644 Binary files a/build/windows/dist/drivers/arduino.cat and b/build/windows/dist/drivers/arduino.cat differ diff --git a/build/windows/dist/drivers/arduino.inf b/build/windows/dist/drivers/arduino.inf index bf3dd829147..1bb76ede1d0 100644 --- a/build/windows/dist/drivers/arduino.inf +++ b/build/windows/dist/drivers/arduino.inf @@ -1,7 +1,7 @@ ; Copyright 2012 Blacklabel Development, Inc. [Strings] -DriverPackageDisplayName="Arduino Boards" +DriverPackageDisplayName="Arduino USB Driver" ManufacturerName="Arduino LLC (www.arduino.cc)" ServiceName="USB RS-232 Emulation Driver" due.bossa.name="Bossa Program Port" @@ -22,6 +22,12 @@ micro.sketch.name="Arduino Micro" uno.name="Arduino Uno" unoR3.name="Arduino Uno" usbserial.name="Arduino USB Serial Light Adapter" +robotControl.bootloader.name="Arduino Robot Control bootloader" +robotControl.sketch.name="Arduino Robot" +robotMotor.bootloader.name="Arduino Robot Motor bootloader" +robotMotor.sketch.name="Arduino Robot" +yun.bootloader.name="Arduino Yun bootloader" +yun.sketch.name="Arduino Yun" [DefaultInstall] CopyINF=arduino.inf @@ -33,7 +39,7 @@ Signature="$Windows NT$" Provider=%ManufacturerName% DriverPackageDisplayName=%DriverPackageDisplayName% CatalogFile=arduino.cat -DriverVer=01/01/2013,1.0.0.0 +DriverVer=01/04/2013,1.0.0.0 [Manufacturer] %ManufacturerName%=DeviceList, NTamd64, NTia64 @@ -61,6 +67,12 @@ DefaultDestDir=12 %uno.name%=DriverInstall, USB\VID_2341&PID_0001 %unoR3.name%=DriverInstall, USB\VID_2341&PID_0043 %usbserial.name%=DriverInstall, USB\VID_2341&PID_003B +%robotControl.bootloader.name%=DriverInstall, USB\VID_2341&PID_0038 +%robotControl.sketch.name%=DriverInstall, USB\VID_2341&PID_8038&MI_00 +%robotMotor.bootloader.name%=DriverInstall, USB\VID_2341&PID_0039 +%robotMotor.sketch.name%=DriverInstall, USB\VID_2341&PID_8039&MI_00 +%yun.bootloader.name%=DriverInstall, USB\VID_2341&PID_0041 +%yun.sketch.name%=DriverInstall, USB\VID_2341&PID_8041&MI_00 [DeviceList.NTamd64] %due.bossa.name%=DriverInstall, USB\VID_03EB&PID_6124 @@ -81,6 +93,12 @@ DefaultDestDir=12 %uno.name%=DriverInstall, USB\VID_2341&PID_0001 %unoR3.name%=DriverInstall, USB\VID_2341&PID_0043 %usbserial.name%=DriverInstall, USB\VID_2341&PID_003B +%robotControl.bootloader.name%=DriverInstall, USB\VID_2341&PID_0038 +%robotControl.sketch.name%=DriverInstall, USB\VID_2341&PID_8038&MI_00 +%robotMotor.bootloader.name%=DriverInstall, USB\VID_2341&PID_0039 +%robotMotor.sketch.name%=DriverInstall, USB\VID_2341&PID_8039&MI_00 +%yun.bootloader.name%=DriverInstall, USB\VID_2341&PID_0041 +%yun.sketch.name%=DriverInstall, USB\VID_2341&PID_8041&MI_00 [DeviceList.NTia64] %esplora.bootloader.name%=DriverInstall, USB\VID_2341&PID_003C @@ -98,6 +116,12 @@ DefaultDestDir=12 %uno.name%=DriverInstall, USB\VID_2341&PID_0001 %unoR3.name%=DriverInstall, USB\VID_2341&PID_0043 %usbserial.name%=DriverInstall, USB\VID_2341&PID_003B +%robotControl.bootloader.name%=DriverInstall, USB\VID_2341&PID_0038 +%robotControl.sketch.name%=DriverInstall, USB\VID_2341&PID_8038&MI_00 +%robotMotor.bootloader.name%=DriverInstall, USB\VID_2341&PID_0039 +%robotMotor.sketch.name%=DriverInstall, USB\VID_2341&PID_8039&MI_00 +%yun.bootloader.name%=DriverInstall, USB\VID_2341&PID_0041 +%yun.sketch.name%=DriverInstall, USB\VID_2341&PID_8041&MI_00 [DriverInstall] include=mdmcpq.inf,usb.inf diff --git a/build/windows/dist/drivers/dpinst-amd64.exe b/build/windows/dist/drivers/dpinst-amd64.exe new file mode 100755 index 00000000000..0507e7388cf Binary files /dev/null and b/build/windows/dist/drivers/dpinst-amd64.exe differ diff --git a/build/windows/dist/drivers/dpinst-x86.exe b/build/windows/dist/drivers/dpinst-x86.exe new file mode 100755 index 00000000000..41a890d1131 Binary files /dev/null and b/build/windows/dist/drivers/dpinst-x86.exe differ diff --git a/build/windows/launcher/config_debug.xml b/build/windows/launcher/config_debug.xml new file mode 100644 index 00000000000..1cab4290866 --- /dev/null +++ b/build/windows/launcher/config_debug.xml @@ -0,0 +1,38 @@ + + true + console + lib + arduino_debug.exe + + + . + normal + http://java.sun.com/javase/downloads/ + + false + false + + application.ico + + processing.app.Base + lib/pde.jar + lib/core.jar + lib/jna.jar + lib/ecj.jar + lib/RXTXcomm.jar + + + java + 1.5.0 + + preferJre + -Xms128m -Xmx128m + + + An error occurred while starting the application. + This application was configured to use a bundled Java Runtime Environment but the runtime is missing or corrupted. + This application requires at least Java Development Kit + The registry refers to a nonexistent Java Development Kit installation or the runtime is corrupted. + An application instance is already running. + + diff --git a/build/windows/launcher/launch4j/.classpath b/build/windows/launcher/launch4j/.classpath deleted file mode 100755 index 734d175a61f..00000000000 --- a/build/windows/launcher/launch4j/.classpath +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/build/windows/launcher/launch4j/.project b/build/windows/launcher/launch4j/.project deleted file mode 100755 index 1c1309dfaf2..00000000000 --- a/build/windows/launcher/launch4j/.project +++ /dev/null @@ -1,17 +0,0 @@ - - - launch4j - - - - - - org.eclipse.jdt.core.javabuilder - - - - - - org.eclipse.jdt.core.javanature - - diff --git a/build/windows/launcher/launch4j/.settings/org.eclipse.jdt.core.prefs b/build/windows/launcher/launch4j/.settings/org.eclipse.jdt.core.prefs deleted file mode 100755 index 056498058fa..00000000000 --- a/build/windows/launcher/launch4j/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,12 +0,0 @@ -#Sun Jul 20 14:10:30 CEST 2008 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.4 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.4 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning -org.eclipse.jdt.core.compiler.source=1.4 diff --git a/build/windows/launcher/launch4j/LICENSE.txt b/build/windows/launcher/launch4j/LICENSE.txt deleted file mode 100755 index 82223322f56..00000000000 --- a/build/windows/launcher/launch4j/LICENSE.txt +++ /dev/null @@ -1,30 +0,0 @@ -Launch4j (http://launch4j.sourceforge.net/) -Cross-platform Java application wrapper for creating Windows native executables. - -Copyright (c) 2004, 2008 Grzegorz Kowal - -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/build/windows/launcher/launch4j/bin/COPYING b/build/windows/launcher/launch4j/bin/COPYING deleted file mode 100755 index 60549be514a..00000000000 --- a/build/windows/launcher/launch4j/bin/COPYING +++ /dev/null @@ -1,340 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc. - 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Library General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) 19yy - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) 19yy name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Library General -Public License instead of this License. diff --git a/build/windows/launcher/launch4j/bin/ld.exe b/build/windows/launcher/launch4j/bin/ld.exe deleted file mode 100755 index f388b95133a..00000000000 Binary files a/build/windows/launcher/launch4j/bin/ld.exe and /dev/null differ diff --git a/build/windows/launcher/launch4j/bin/windres.exe b/build/windows/launcher/launch4j/bin/windres.exe deleted file mode 100755 index 4ad2ae98a78..00000000000 Binary files a/build/windows/launcher/launch4j/bin/windres.exe and /dev/null differ diff --git a/build/windows/launcher/launch4j/build.xml b/build/windows/launcher/launch4j/build.xml deleted file mode 100755 index a7682ce0c01..00000000000 --- a/build/windows/launcher/launch4j/build.xml +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/build/windows/launcher/launch4j/demo/ConsoleApp/ConsoleApp.exe b/build/windows/launcher/launch4j/demo/ConsoleApp/ConsoleApp.exe deleted file mode 100755 index d8a8f75d03e..00000000000 Binary files a/build/windows/launcher/launch4j/demo/ConsoleApp/ConsoleApp.exe and /dev/null differ diff --git a/build/windows/launcher/launch4j/demo/ConsoleApp/ConsoleApp.jar b/build/windows/launcher/launch4j/demo/ConsoleApp/ConsoleApp.jar deleted file mode 100755 index 6d4b126e6f1..00000000000 Binary files a/build/windows/launcher/launch4j/demo/ConsoleApp/ConsoleApp.jar and /dev/null differ diff --git a/build/windows/launcher/launch4j/demo/ConsoleApp/build.bat b/build/windows/launcher/launch4j/demo/ConsoleApp/build.bat deleted file mode 100755 index ed5f704e306..00000000000 --- a/build/windows/launcher/launch4j/demo/ConsoleApp/build.bat +++ /dev/null @@ -1,14 +0,0 @@ -@echo off -if "%ANT_HOME%"=="" goto noAntHome -if "%JAVA_HOME%"=="" goto noJavaHome -call "%ANT_HOME%\bin\ant.bat" exe -goto end - -:noAntHome -echo ANT_HOME environment variable is not set -goto end - -:noJavaHome -echo JAVA_HOME environment variable is not set - -:end diff --git a/build/windows/launcher/launch4j/demo/ConsoleApp/build.xml b/build/windows/launcher/launch4j/demo/ConsoleApp/build.xml deleted file mode 100755 index 5f3473da651..00000000000 --- a/build/windows/launcher/launch4j/demo/ConsoleApp/build.xml +++ /dev/null @@ -1,57 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/build/windows/launcher/launch4j/demo/ConsoleApp/l4j/ConsoleApp.ico b/build/windows/launcher/launch4j/demo/ConsoleApp/l4j/ConsoleApp.ico deleted file mode 100755 index cc4c540e2d1..00000000000 Binary files a/build/windows/launcher/launch4j/demo/ConsoleApp/l4j/ConsoleApp.ico and /dev/null differ diff --git a/build/windows/launcher/launch4j/demo/ConsoleApp/lib/readme.txt b/build/windows/launcher/launch4j/demo/ConsoleApp/lib/readme.txt deleted file mode 100755 index ef44ded3a1a..00000000000 --- a/build/windows/launcher/launch4j/demo/ConsoleApp/lib/readme.txt +++ /dev/null @@ -1,8 +0,0 @@ -Put your jar libs here and the build script will include them -in the classpath stored inside the jar manifest. -In order to run your application move the output exe file from -the dist directory to the same level as lib. - -SimpleApp.exe -lib/ -lib/xml.jar diff --git a/build/windows/launcher/launch4j/demo/ConsoleApp/readme.txt b/build/windows/launcher/launch4j/demo/ConsoleApp/readme.txt deleted file mode 100755 index fa38dc8bd2f..00000000000 --- a/build/windows/launcher/launch4j/demo/ConsoleApp/readme.txt +++ /dev/null @@ -1 +0,0 @@ -To build the example application set JAVA_HOME and ANT_HOME environment variables. diff --git a/build/windows/launcher/launch4j/demo/ConsoleApp/src/net/sf/launch4j/example/ConsoleApp.java b/build/windows/launcher/launch4j/demo/ConsoleApp/src/net/sf/launch4j/example/ConsoleApp.java deleted file mode 100755 index eb1398c2c5f..00000000000 --- a/build/windows/launcher/launch4j/demo/ConsoleApp/src/net/sf/launch4j/example/ConsoleApp.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -package net.sf.launch4j.example; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - -/** - * @author Copyright (C) 2005 Grzegorz Kowal - */ -public class ConsoleApp { - public static void main(String[] args) { - StringBuffer sb = new StringBuffer("Hello World!\n\nJava version: "); - sb.append(System.getProperty("java.version")); - sb.append("\nJava home: "); - sb.append(System.getProperty("java.home")); - sb.append("\nCurrent dir: "); - sb.append(System.getProperty("user.dir")); - if (args.length > 0) { - sb.append("\nArgs: "); - for (int i = 0; i < args.length; i++) { - sb.append(args[i]); - sb.append(' '); - } - } - sb.append("\n\nEnter a line of text, Ctrl-C to stop.\n\n>"); - System.out.print(sb.toString()); - try { - BufferedReader is = new BufferedReader(new InputStreamReader(System.in)); - String line; - while ((line = is.readLine()) != null && !line.equalsIgnoreCase("quit")) { - System.out.print("You wrote: " + line + "\n\n>"); - } - is.close(); - System.exit(123); - } catch (IOException e) { - System.err.print(e); - } - } -} diff --git a/build/windows/launcher/launch4j/demo/LICENSE.txt b/build/windows/launcher/launch4j/demo/LICENSE.txt deleted file mode 100755 index d6d6bb5eac1..00000000000 --- a/build/windows/launcher/launch4j/demo/LICENSE.txt +++ /dev/null @@ -1,30 +0,0 @@ -Launch4j (http://launch4j.sourceforge.net/) -Cross-platform Java application wrapper for creating Windows native executables. - -Copyright (c) 2004, 2007 Grzegorz Kowal - -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/build/windows/launcher/launch4j/demo/SimpleApp/SimpleApp.exe b/build/windows/launcher/launch4j/demo/SimpleApp/SimpleApp.exe deleted file mode 100755 index 1a75fc298e4..00000000000 Binary files a/build/windows/launcher/launch4j/demo/SimpleApp/SimpleApp.exe and /dev/null differ diff --git a/build/windows/launcher/launch4j/demo/SimpleApp/SimpleApp.jar b/build/windows/launcher/launch4j/demo/SimpleApp/SimpleApp.jar deleted file mode 100755 index f02c6133b7d..00000000000 Binary files a/build/windows/launcher/launch4j/demo/SimpleApp/SimpleApp.jar and /dev/null differ diff --git a/build/windows/launcher/launch4j/demo/SimpleApp/build.bat b/build/windows/launcher/launch4j/demo/SimpleApp/build.bat deleted file mode 100755 index ed5f704e306..00000000000 --- a/build/windows/launcher/launch4j/demo/SimpleApp/build.bat +++ /dev/null @@ -1,14 +0,0 @@ -@echo off -if "%ANT_HOME%"=="" goto noAntHome -if "%JAVA_HOME%"=="" goto noJavaHome -call "%ANT_HOME%\bin\ant.bat" exe -goto end - -:noAntHome -echo ANT_HOME environment variable is not set -goto end - -:noJavaHome -echo JAVA_HOME environment variable is not set - -:end diff --git a/build/windows/launcher/launch4j/demo/SimpleApp/build.xml b/build/windows/launcher/launch4j/demo/SimpleApp/build.xml deleted file mode 100755 index 82f4b49980b..00000000000 --- a/build/windows/launcher/launch4j/demo/SimpleApp/build.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/build/windows/launcher/launch4j/demo/SimpleApp/l4j/SimpleApp.ico b/build/windows/launcher/launch4j/demo/SimpleApp/l4j/SimpleApp.ico deleted file mode 100755 index cc4c540e2d1..00000000000 Binary files a/build/windows/launcher/launch4j/demo/SimpleApp/l4j/SimpleApp.ico and /dev/null differ diff --git a/build/windows/launcher/launch4j/demo/SimpleApp/l4j/SimpleApp.xml b/build/windows/launcher/launch4j/demo/SimpleApp/l4j/SimpleApp.xml deleted file mode 100755 index 9a7dc940a62..00000000000 --- a/build/windows/launcher/launch4j/demo/SimpleApp/l4j/SimpleApp.xml +++ /dev/null @@ -1,18 +0,0 @@ - - gui - ../SimpleApp.jar - ../SimpleApp.exe - SimpleApp - . - true - SimpleApp.ico - - 1.4.0 - - - splash.bmp - true - 60 - true - - \ No newline at end of file diff --git a/build/windows/launcher/launch4j/demo/SimpleApp/l4j/splash.bmp b/build/windows/launcher/launch4j/demo/SimpleApp/l4j/splash.bmp deleted file mode 100755 index 88d7bbf10fd..00000000000 Binary files a/build/windows/launcher/launch4j/demo/SimpleApp/l4j/splash.bmp and /dev/null differ diff --git a/build/windows/launcher/launch4j/demo/SimpleApp/lib/readme.txt b/build/windows/launcher/launch4j/demo/SimpleApp/lib/readme.txt deleted file mode 100755 index ef44ded3a1a..00000000000 --- a/build/windows/launcher/launch4j/demo/SimpleApp/lib/readme.txt +++ /dev/null @@ -1,8 +0,0 @@ -Put your jar libs here and the build script will include them -in the classpath stored inside the jar manifest. -In order to run your application move the output exe file from -the dist directory to the same level as lib. - -SimpleApp.exe -lib/ -lib/xml.jar diff --git a/build/windows/launcher/launch4j/demo/SimpleApp/readme.txt b/build/windows/launcher/launch4j/demo/SimpleApp/readme.txt deleted file mode 100755 index fa38dc8bd2f..00000000000 --- a/build/windows/launcher/launch4j/demo/SimpleApp/readme.txt +++ /dev/null @@ -1 +0,0 @@ -To build the example application set JAVA_HOME and ANT_HOME environment variables. diff --git a/build/windows/launcher/launch4j/demo/SimpleApp/src/net/sf/launch4j/example/SimpleApp.java b/build/windows/launcher/launch4j/demo/SimpleApp/src/net/sf/launch4j/example/SimpleApp.java deleted file mode 100755 index 8e87c595391..00000000000 --- a/build/windows/launcher/launch4j/demo/SimpleApp/src/net/sf/launch4j/example/SimpleApp.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -package net.sf.launch4j.example; - -import java.awt.Dimension; -import java.awt.Toolkit; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; - -import javax.swing.JFrame; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JMenuItem; -import javax.swing.JOptionPane; -import javax.swing.UIManager; - -public class SimpleApp extends JFrame { - public SimpleApp(String[] args) { - super("Java Application"); - final int inset = 100; - Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); - setBounds (inset, inset, - screenSize.width - inset * 2, screenSize.height - inset * 2); - - JMenu menu = new JMenu("File"); - menu.add(new JMenuItem("Open")); - menu.add(new JMenuItem("Save")); - JMenuBar mb = new JMenuBar(); - mb.setOpaque(true); - mb.add(menu); - setJMenuBar(mb); - - this.addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) { - System.exit(123); - }}); - setVisible(true); - - StringBuffer sb = new StringBuffer("Java version: "); - sb.append(System.getProperty("java.version")); - sb.append("\nJava home: "); - sb.append(System.getProperty("java.home")); - sb.append("\nCurrent dir: "); - sb.append(System.getProperty("user.dir")); - if (args.length > 0) { - sb.append("\nArgs: "); - for (int i = 0; i < args.length; i++) { - sb.append(args[i]); - sb.append(' '); - } - } - JOptionPane.showMessageDialog(this, - sb.toString(), - "Info", - JOptionPane.INFORMATION_MESSAGE); - } - - public static void setLAF() { - JFrame.setDefaultLookAndFeelDecorated(true); - Toolkit.getDefaultToolkit().setDynamicLayout(true); - System.setProperty("sun.awt.noerasebackground","true"); - try { - UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); - } catch (Exception e) { - System.err.println("Failed to set LookAndFeel"); - } - } - - public static void main(String[] args) { - setLAF(); - new SimpleApp(args); - } -} diff --git a/build/windows/launcher/launch4j/demo/readme.txt b/build/windows/launcher/launch4j/demo/readme.txt deleted file mode 100755 index f5917821449..00000000000 --- a/build/windows/launcher/launch4j/demo/readme.txt +++ /dev/null @@ -1,3 +0,0 @@ -JRE/SDK 1.4.0 or higher must be installed on your system to run this demo. - -try running it with some command line arguments... diff --git a/build/windows/launcher/launch4j/head/LICENSE.txt b/build/windows/launcher/launch4j/head/LICENSE.txt deleted file mode 100755 index 536488e6149..00000000000 --- a/build/windows/launcher/launch4j/head/LICENSE.txt +++ /dev/null @@ -1,23 +0,0 @@ -Copyright (c) 2004, 2007 Grzegorz Kowal - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -Except as contained in this notice, the name(s) of the above copyright holders -shall not be used in advertising or otherwise to promote the sale, use or other -dealings in this Software without prior written authorization. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file diff --git a/build/windows/launcher/launch4j/head/guihead.o b/build/windows/launcher/launch4j/head/guihead.o deleted file mode 100644 index 6d590470d92..00000000000 Binary files a/build/windows/launcher/launch4j/head/guihead.o and /dev/null differ diff --git a/build/windows/launcher/launch4j/head/head.o b/build/windows/launcher/launch4j/head/head.o deleted file mode 100644 index 4719bd34f8b..00000000000 Binary files a/build/windows/launcher/launch4j/head/head.o and /dev/null differ diff --git a/build/windows/launcher/launch4j/head_src/LICENSE.txt b/build/windows/launcher/launch4j/head_src/LICENSE.txt deleted file mode 100755 index 2805f412a16..00000000000 --- a/build/windows/launcher/launch4j/head_src/LICENSE.txt +++ /dev/null @@ -1,23 +0,0 @@ -Copyright (c) 2004, 2008 Grzegorz Kowal - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -Except as contained in this notice, the name(s) of the above copyright holders -shall not be used in advertising or otherwise to promote the sale, use or other -dealings in this Software without prior written authorization. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/build/windows/launcher/launch4j/head_src/consolehead/Makefile.win b/build/windows/launcher/launch4j/head_src/consolehead/Makefile.win deleted file mode 100755 index 349e4c00f5c..00000000000 --- a/build/windows/launcher/launch4j/head_src/consolehead/Makefile.win +++ /dev/null @@ -1,33 +0,0 @@ -# Project: consolehead -# Makefile created by Dev-C++ 4.9.9.2 - -CPP = g++.exe -CC = gcc.exe -WINDRES = windres.exe -RES = -OBJ = ../../head/consolehead.o ../../head/head.o $(RES) -LINKOBJ = ../../head/consolehead.o ../../head/head.o $(RES) -LIBS = -L"C:/Dev-Cpp/lib" -n -s -INCS = -I"C:/Dev-Cpp/include" -CXXINCS = -I"C:/Dev-Cpp/lib/gcc/mingw32/3.4.2/include" -I"C:/Dev-Cpp/include/c++/3.4.2/backward" -I"C:/Dev-Cpp/include/c++/3.4.2/mingw32" -I"C:/Dev-Cpp/include/c++/3.4.2" -I"C:/Dev-Cpp/include" -BIN = consolehead.exe -CXXFLAGS = $(CXXINCS) -fexpensive-optimizations -O3 -CFLAGS = $(INCS) -fexpensive-optimizations -O3 -RM = rm -f - -.PHONY: all all-before all-after clean clean-custom - -all: all-before consolehead.exe all-after - - -clean: clean-custom - ${RM} $(OBJ) $(BIN) - -$(BIN): $(OBJ) -# $(CC) $(LINKOBJ) -o "consolehead.exe" $(LIBS) - -../../head/consolehead.o: consolehead.c - $(CC) -c consolehead.c -o ../../head/consolehead.o $(CFLAGS) - -../../head/head.o: ../head.c - $(CC) -c ../head.c -o ../../head/head.o $(CFLAGS) diff --git a/build/windows/launcher/launch4j/head_src/consolehead/consolehead.c b/build/windows/launcher/launch4j/head_src/consolehead/consolehead.c deleted file mode 100755 index 755a7673c10..00000000000 --- a/build/windows/launcher/launch4j/head_src/consolehead/consolehead.c +++ /dev/null @@ -1,65 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - Except as contained in this notice, the name(s) of the above copyright holders - shall not be used in advertising or otherwise to promote the sale, use or other - dealings in this Software without prior written authorization. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -#include "../resource.h" -#include "../head.h" - -int main(int argc, char* argv[]) -{ - setConsoleFlag(); - LPTSTR cmdLine = GetCommandLine(); - if (*cmdLine == '"') { - if (*(cmdLine = strchr(cmdLine + 1, '"') + 1)) { - cmdLine++; - } - } else if ((cmdLine = strchr(cmdLine, ' ')) != NULL) { - cmdLine++; - } else { - cmdLine = ""; - } - int result = prepare(cmdLine); - if (result == ERROR_ALREADY_EXISTS) { - char errMsg[BIG_STR] = {0}; - loadString(INSTANCE_ALREADY_EXISTS_MSG, errMsg); - msgBox(errMsg); - closeLogFile(); - return 2; - } - if (result != TRUE) { - signalError(); - return 1; - } - - result = (int) execute(TRUE); - if (result == -1) { - signalError(); - } else { - return result; - } -} diff --git a/build/windows/launcher/launch4j/head_src/consolehead/consolehead.dev b/build/windows/launcher/launch4j/head_src/consolehead/consolehead.dev deleted file mode 100755 index a309ec94f65..00000000000 --- a/build/windows/launcher/launch4j/head_src/consolehead/consolehead.dev +++ /dev/null @@ -1,108 +0,0 @@ -[Project] -FileName=consolehead.dev -Name=consolehead -UnitCount=4 -Type=1 -Ver=1 -ObjFiles= -Includes= -Libs= -PrivateResource= -ResourceIncludes= -MakeIncludes= -Compiler= -CppCompiler= -Linker=-n_@@_ -IsCpp=0 -Icon= -ExeOutput= -ObjectOutput=..\..\head -OverrideOutput=0 -OverrideOutputName=consolehead.exe -HostApplication= -Folders= -CommandLine= -UseCustomMakefile=0 -CustomMakefile=Makefile.win -IncludeVersionInfo=0 -SupportXPThemes=0 -CompilerSet=0 -CompilerSettings=0000000001001000000100 - -[Unit1] -FileName=consolehead.c -CompileCpp=0 -Folder=consolehead -Compile=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - -[VersionInfo] -Major=0 -Minor=1 -Release=1 -Build=1 -LanguageID=1033 -CharsetID=1252 -CompanyName= -FileVersion= -FileDescription=Developed using the Dev-C++ IDE -InternalName= -LegalCopyright= -LegalTrademarks= -OriginalFilename= -ProductName= -ProductVersion= -AutoIncBuildNr=0 - -[Unit2] -FileName=..\resource.h -CompileCpp=0 -Folder=consolehead -Compile=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - -[Unit3] -FileName=..\head.c -CompileCpp=0 -Folder=consolehead -Compile=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - -[Unit4] -FileName=..\head.h -CompileCpp=0 -Folder=consolehead -Compile=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - -[Unit5] -FileName=..\head.rc -Folder=consolehead -Compile=1 -Link=0 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - -[Unit6] -FileName=..\resid.h -CompileCpp=0 -Folder=consolehead -Compile=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - diff --git a/build/windows/launcher/launch4j/head_src/guihead/Makefile.win b/build/windows/launcher/launch4j/head_src/guihead/Makefile.win deleted file mode 100755 index 3c642f8fcf7..00000000000 --- a/build/windows/launcher/launch4j/head_src/guihead/Makefile.win +++ /dev/null @@ -1,38 +0,0 @@ -# Project: guihead -# Makefile created by Dev-C++ 4.9.9.2 - -CPP = g++.exe -CC = gcc.exe -WINDRES = windres.exe -RES = -OBJ = ../../head/guihead.o ../../head/head.o $(RES) -LINKOBJ = ../../head/guihead.o ../../head/head.o $(RES) - -# removed dev-cpp flags, replacing for cygwin/mingw [fry] -CXXFLAGS = -mwindows -mno-cygwin -O2 -Wall -CFLAGS = -mwindows -mno-cygwin -O2 -Wall -#CFLAGS = -I/cygdrive/c/cygwin/usr/include/mingw -#LIBS = -L"C:/Dev-Cpp/lib" -mwindows -n -s -#INCS = -I"C:/Dev-Cpp/include" -#CXXINCS = -I"C:/Dev-Cpp/lib/gcc/mingw32/3.4.2/include" -I"C:/Dev-Cpp/include/c++/3.4.2/backward" -I"C:/Dev-Cpp/include/c++/3.4.2/mingw32" -I"C:/Dev-Cpp/include/c++/3.4.2" -I"C:/Dev-Cpp/include" -BIN = guihead.exe -#CXXFLAGS = $(CXXINCS) -fexpensive-optimizations -O3 -#CFLAGS = $(INCS) -fexpensive-optimizations -O3 -RM = rm -f - -.PHONY: all all-before all-after clean clean-custom - -all: all-before guihead.exe all-after - - -clean: clean-custom - ${RM} $(OBJ) $(BIN) - -$(BIN): $(OBJ) -# $(CC) $(LINKOBJ) -o "guihead.exe" $(LIBS) - -../../head/guihead.o: guihead.c - $(CC) -c guihead.c -o ../../head/guihead.o $(CFLAGS) - -../../head/head.o: ../head.c - $(CC) -c ../head.c -o ../../head/head.o $(CFLAGS) diff --git a/build/windows/launcher/launch4j/head_src/guihead/guihead.c b/build/windows/launcher/launch4j/head_src/guihead/guihead.c deleted file mode 100755 index 508a5bdacbf..00000000000 --- a/build/windows/launcher/launch4j/head_src/guihead/guihead.c +++ /dev/null @@ -1,185 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - Sylvain Mina (single instance patch) - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - Except as contained in this notice, the name(s) of the above copyright holders - shall not be used in advertising or otherwise to promote the sale, use or other - dealings in this Software without prior written authorization. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -#include "../resource.h" -#include "../head.h" -#include "guihead.h" - -extern FILE* hLog; -extern PROCESS_INFORMATION pi; - -HWND hWnd; -DWORD dwExitCode = 0; -BOOL stayAlive = FALSE; -BOOL splash = FALSE; -BOOL splashTimeoutErr; -BOOL waitForWindow; -int splashTimeout = DEFAULT_SPLASH_TIMEOUT; - -int APIENTRY WinMain(HINSTANCE hInstance, - HINSTANCE hPrevInstance, - LPSTR lpCmdLine, - int nCmdShow) { - int result = prepare(lpCmdLine); - if (result == ERROR_ALREADY_EXISTS) { - HWND handle = getInstanceWindow(); - ShowWindow(handle, SW_SHOW); - SetForegroundWindow(handle); - closeLogFile(); - return 2; - } - if (result != TRUE) { - signalError(); - return 1; - } - - splash = loadBool(SHOW_SPLASH) - && strstr(lpCmdLine, "--l4j-no-splash") == NULL; - stayAlive = loadBool(GUI_HEADER_STAYS_ALIVE) - && strstr(lpCmdLine, "--l4j-dont-wait") == NULL; - if (splash || stayAlive) { - hWnd = CreateWindowEx(WS_EX_TOOLWINDOW, "STATIC", "", - WS_POPUP | SS_BITMAP, - 0, 0, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL); - if (splash) { - char timeout[10] = {0}; - if (loadString(SPLASH_TIMEOUT, timeout)) { - splashTimeout = atoi(timeout); - if (splashTimeout <= 0 || splashTimeout > MAX_SPLASH_TIMEOUT) { - splashTimeout = DEFAULT_SPLASH_TIMEOUT; - } - } - splashTimeoutErr = loadBool(SPLASH_TIMEOUT_ERR) - && strstr(lpCmdLine, "--l4j-no-splash-err") == NULL; - waitForWindow = loadBool(SPLASH_WAITS_FOR_WINDOW); - HANDLE hImage = LoadImage(hInstance, // handle of the instance containing the image - MAKEINTRESOURCE(SPLASH_BITMAP), // name or identifier of image - IMAGE_BITMAP, // type of image - 0, // desired width - 0, // desired height - LR_DEFAULTSIZE); - if (hImage == NULL) { - signalError(); - return 1; - } - SendMessage(hWnd, STM_SETIMAGE, IMAGE_BITMAP, (LPARAM) hImage); - RECT rect; - GetWindowRect(hWnd, &rect); - int x = (GetSystemMetrics(SM_CXSCREEN) - (rect.right - rect.left)) / 2; - int y = (GetSystemMetrics(SM_CYSCREEN) - (rect.bottom - rect.top)) / 2; - SetWindowPos(hWnd, HWND_TOP, x, y, 0, 0, SWP_NOSIZE); - ShowWindow(hWnd, nCmdShow); - UpdateWindow (hWnd); - } - if (!SetTimer (hWnd, ID_TIMER, 1000 /* 1s */, TimerProc)) { - signalError(); - return 1; - } - } - if (execute(FALSE) == -1) { - signalError(); - return 1; - } - if (!(splash || stayAlive)) { - debug("Exit code:\t0\n"); - closeHandles(); - return 0; - } - - MSG msg; - while (GetMessage(&msg, NULL, 0, 0)) { - TranslateMessage(&msg); - DispatchMessage(&msg); - } - debug("Exit code:\t%d\n", dwExitCode); - closeHandles(); - return dwExitCode; -} - -HWND getInstanceWindow() { - char windowTitle[STR]; - char instWindowTitle[STR] = {0}; - if (loadString(INSTANCE_WINDOW_TITLE, instWindowTitle)) { - HWND handle = FindWindowEx(NULL, NULL, NULL, NULL); - while (handle != NULL) { - GetWindowText(handle, windowTitle, STR - 1); - if (strstr(windowTitle, instWindowTitle) != NULL) { - return handle; - } else { - handle = FindWindowEx(NULL, handle, NULL, NULL); - } - } - } - return NULL; -} - -BOOL CALLBACK enumwndfn(HWND hwnd, LPARAM lParam) { - DWORD processId; - GetWindowThreadProcessId(hwnd, &processId); - if (pi.dwProcessId == processId) { - LONG styles = GetWindowLong(hwnd, GWL_STYLE); - if ((styles & WS_VISIBLE) != 0) { - splash = FALSE; - ShowWindow(hWnd, SW_HIDE); - return FALSE; - } - } - return TRUE; -} - -VOID CALLBACK TimerProc( - HWND hwnd, // handle of window for timer messages - UINT uMsg, // WM_TIMER message - UINT idEvent, // timer identifier - DWORD dwTime) { // current system time - - if (splash) { - if (splashTimeout == 0) { - splash = FALSE; - ShowWindow(hWnd, SW_HIDE); - if (waitForWindow && splashTimeoutErr) { - KillTimer(hwnd, ID_TIMER); - signalError(); - PostQuitMessage(0); - } - } else { - splashTimeout--; - if (waitForWindow) { - EnumWindows(enumwndfn, 0); - } - } - } - GetExitCodeProcess(pi.hProcess, &dwExitCode); - if (dwExitCode != STILL_ACTIVE - || !(splash || stayAlive)) { - KillTimer(hWnd, ID_TIMER); - PostQuitMessage(0); - } -} diff --git a/build/windows/launcher/launch4j/head_src/guihead/guihead.dev b/build/windows/launcher/launch4j/head_src/guihead/guihead.dev deleted file mode 100755 index 7c30088f11b..00000000000 --- a/build/windows/launcher/launch4j/head_src/guihead/guihead.dev +++ /dev/null @@ -1,109 +0,0 @@ -[Project] -FileName=guihead.dev -Name=guihead -UnitCount=5 -Type=0 -Ver=1 -ObjFiles= -Includes= -Libs= -PrivateResource= -ResourceIncludes= -MakeIncludes= -Compiler= -CppCompiler= -Linker=-n_@@_ -IsCpp=0 -Icon= -ExeOutput= -ObjectOutput=..\..\head -OverrideOutput=0 -OverrideOutputName=guihead.exe -HostApplication= -Folders= -CommandLine= -UseCustomMakefile=1 -CustomMakefile=Makefile.win -IncludeVersionInfo=0 -SupportXPThemes=0 -CompilerSet=0 -CompilerSettings=0000000001001000000100 - -[Unit1] -FileName=guihead.c -CompileCpp=0 -Folder=guihead -Compile=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd=$(CC) -c guihead.c -o ../../head/guihead.o $(CFLAGS) - -[Unit2] -FileName=guihead.h -CompileCpp=0 -Folder=guihead -Compile=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - -[VersionInfo] -Major=0 -Minor=1 -Release=1 -Build=1 -LanguageID=1033 -CharsetID=1252 -CompanyName= -FileVersion= -FileDescription=Developed using the Dev-C++ IDE -InternalName= -LegalCopyright= -LegalTrademarks= -OriginalFilename= -ProductName= -ProductVersion= -AutoIncBuildNr=0 - -[Unit4] -FileName=..\head.h -CompileCpp=0 -Folder=guihead -Compile=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - -[Unit6] -FileName=..\resid.h -CompileCpp=0 -Folder=guihead -Compile=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - -[Unit3] -FileName=..\head.c -CompileCpp=0 -Folder=guihead -Compile=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - -[Unit5] -FileName=..\resource.h -CompileCpp=0 -Folder=guihead -Compile=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - diff --git a/build/windows/launcher/launch4j/head_src/guihead/guihead.h b/build/windows/launcher/launch4j/head_src/guihead/guihead.h deleted file mode 100755 index 2fc71e31f32..00000000000 --- a/build/windows/launcher/launch4j/head_src/guihead/guihead.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - Except as contained in this notice, the name(s) of the above copyright holders - shall not be used in advertising or otherwise to promote the sale, use or other - dealings in this Software without prior written authorization. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -#define ID_TIMER 1 -#define DEFAULT_SPLASH_TIMEOUT 60 /* 60 seconds */ -#define MAX_SPLASH_TIMEOUT 60 * 15 /* 15 minutes */ - -HWND getInstanceWindow(); - -BOOL CALLBACK enumwndfn(HWND hwnd, LPARAM lParam); - -VOID CALLBACK TimerProc( - HWND hwnd, // handle of window for timer messages - UINT uMsg, // WM_TIMER message - UINT idEvent, // timer identifier - DWORD dwTime // current system time -); diff --git a/build/windows/launcher/launch4j/head_src/head.c b/build/windows/launcher/launch4j/head_src/head.c deleted file mode 100755 index 1ff937694dc..00000000000 --- a/build/windows/launcher/launch4j/head_src/head.c +++ /dev/null @@ -1,818 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2008 Grzegorz Kowal, - Ian Roberts (jdk preference patch) - Sylvain Mina (single instance patch) - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - Except as contained in this notice, the name(s) of the above copyright holders - shall not be used in advertising or otherwise to promote the sale, use or other - dealings in this Software without prior written authorization. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -#include "resource.h" -#include "head.h" - -HMODULE hModule; -FILE* hLog; -BOOL console = FALSE; -BOOL wow64 = FALSE; -int foundJava = NO_JAVA_FOUND; - -struct _stat statBuf; -PROCESS_INFORMATION pi; -DWORD priority; - -char mutexName[STR] = {0}; - -char errUrl[256] = {0}; -char errTitle[STR] = "Launch4j"; -char errMsg[BIG_STR] = {0}; - -char javaMinVer[STR] = {0}; -char javaMaxVer[STR] = {0}; -char foundJavaVer[STR] = {0}; -char foundJavaKey[_MAX_PATH] = {0}; - -char oldPwd[_MAX_PATH] = {0}; -char workingDir[_MAX_PATH] = {0}; -char cmd[_MAX_PATH] = {0}; -char args[MAX_ARGS] = {0}; - -FILE* openLogFile(const char* exePath, const int pathLen) { - char path[_MAX_PATH] = {0}; - strncpy(path, exePath, pathLen); - strcat(path, "\\launch4j.log"); - return fopen(path, "a"); -} - -void closeLogFile() { - if (hLog != NULL) { - fclose(hLog); - } -} - -void setWow64Flag() { - LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress( - GetModuleHandle(TEXT("kernel32")), "IsWow64Process"); - - if (fnIsWow64Process != NULL) { - fnIsWow64Process(GetCurrentProcess(), &wow64); - } - debug("WOW64:\t\t%s\n", wow64 ? "yes" : "no"); -} - -void setConsoleFlag() { - console = TRUE; -} - -void msgBox(const char* text) { - if (console) { - printf("%s: %s\n", errTitle, text); - } else { - MessageBox(NULL, text, errTitle, MB_OK); - } -} - -void signalError() { - DWORD err = GetLastError(); - if (err) { - LPVOID lpMsgBuf; - FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER - | FORMAT_MESSAGE_FROM_SYSTEM - | FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - err, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language - (LPTSTR) &lpMsgBuf, - 0, - NULL); - debug("Error:\t\t%s\n", (LPCTSTR) lpMsgBuf); - strcat(errMsg, "\n\n"); - strcat(errMsg, (LPCTSTR) lpMsgBuf); - msgBox(errMsg); - LocalFree(lpMsgBuf); - } else { - msgBox(errMsg); - } - if (*errUrl) { - debug("Open URL:\t%s\n", errUrl); - ShellExecute(NULL, "open", errUrl, NULL, NULL, SW_SHOWNORMAL); - } - closeLogFile(); -} - -BOOL loadString(const int resID, char* buffer) { - HRSRC hResource; - HGLOBAL hResourceLoaded; - LPBYTE lpBuffer; - - hResource = FindResourceEx(hModule, RT_RCDATA, MAKEINTRESOURCE(resID), - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT)); - if (NULL != hResource) { - hResourceLoaded = LoadResource(hModule, hResource); - if (NULL != hResourceLoaded) { - lpBuffer = (LPBYTE) LockResource(hResourceLoaded); - if (NULL != lpBuffer) { - int x = 0; - do { - buffer[x] = (char) lpBuffer[x]; - } while (buffer[x++] != 0); - // debug("Resource %d:\t%s\n", resID, buffer); - return TRUE; - } - } - } else { - SetLastError(0); - } - return FALSE; -} - -BOOL loadBool(const int resID) { - char boolStr[20] = {0}; - loadString(resID, boolStr); - return strcmp(boolStr, TRUE_STR) == 0; -} - -int loadInt(const int resID) { - char intStr[20] = {0}; - loadString(resID, intStr); - return atoi(intStr); -} - -BOOL regQueryValue(const char* regPath, unsigned char* buffer, - unsigned long bufferLength) { - HKEY hRootKey; - char* key; - char* value; - if (strstr(regPath, HKEY_CLASSES_ROOT_STR) == regPath) { - hRootKey = HKEY_CLASSES_ROOT; - } else if (strstr(regPath, HKEY_CURRENT_USER_STR) == regPath) { - hRootKey = HKEY_CURRENT_USER; - } else if (strstr(regPath, HKEY_LOCAL_MACHINE_STR) == regPath) { - hRootKey = HKEY_LOCAL_MACHINE; - } else if (strstr(regPath, HKEY_USERS_STR) == regPath) { - hRootKey = HKEY_USERS; - } else if (strstr(regPath, HKEY_CURRENT_CONFIG_STR) == regPath) { - hRootKey = HKEY_CURRENT_CONFIG; - } else { - return FALSE; - } - key = strchr(regPath, '\\') + 1; - value = strrchr(regPath, '\\') + 1; - *(value - 1) = 0; - - HKEY hKey; - unsigned long datatype; - BOOL result = FALSE; - if ((wow64 && RegOpenKeyEx(hRootKey, - key, - 0, - KEY_READ | KEY_WOW64_64KEY, - &hKey) == ERROR_SUCCESS) - || RegOpenKeyEx(hRootKey, - key, - 0, - KEY_READ, - &hKey) == ERROR_SUCCESS) { - result = RegQueryValueEx(hKey, value, NULL, &datatype, buffer, &bufferLength) - == ERROR_SUCCESS; - RegCloseKey(hKey); - } - *(value - 1) = '\\'; - return result; -} - -void regSearch(const HKEY hKey, const char* keyName, const int searchType) { - DWORD x = 0; - unsigned long size = BIG_STR; - FILETIME time; - char buffer[BIG_STR] = {0}; - while (RegEnumKeyEx( - hKey, // handle to key to enumerate - x++, // index of subkey to enumerate - buffer, // address of buffer for subkey name - &size, // address for size of subkey buffer - NULL, // reserved - NULL, // address of buffer for class string - NULL, // address for size of class buffer - &time) == ERROR_SUCCESS) { - - if (strcmp(buffer, javaMinVer) >= 0 - && (!*javaMaxVer || strcmp(buffer, javaMaxVer) <= 0) - && strcmp(buffer, foundJavaVer) > 0) { - strcpy(foundJavaVer, buffer); - strcpy(foundJavaKey, keyName); - appendPath(foundJavaKey, buffer); - foundJava = searchType; - debug("Match:\t\t%s\\%s\n", keyName, buffer); - } else { - debug("Ignore:\t\t%s\\%s\n", keyName, buffer); - } - size = BIG_STR; - } -} - -void regSearchWow(const char* keyName, const int searchType) { - HKEY hKey; - debug("64-bit search:\t%s...\n", keyName); - if (wow64 && RegOpenKeyEx(HKEY_LOCAL_MACHINE, - keyName, - 0, - KEY_READ | KEY_WOW64_64KEY, - &hKey) == ERROR_SUCCESS) { - - regSearch(hKey, keyName, searchType | KEY_WOW64_64KEY); - RegCloseKey(hKey); - if ((foundJava & KEY_WOW64_64KEY) != NO_JAVA_FOUND) - { - debug("Using 64-bit runtime.\n"); - return; - } - } - debug("32-bit search:\t%s...\n", keyName); - if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, - keyName, - 0, - KEY_READ, - &hKey) == ERROR_SUCCESS) { - regSearch(hKey, keyName, searchType); - RegCloseKey(hKey); - } -} - -void regSearchJreSdk(const char* jreKeyName, const char* sdkKeyName, - const int jdkPreference) { - if (jdkPreference == JDK_ONLY || jdkPreference == PREFER_JDK) { - regSearchWow(sdkKeyName, FOUND_SDK); - if (jdkPreference != JDK_ONLY) { - regSearchWow(jreKeyName, FOUND_JRE); - } - } else { // jdkPreference == JRE_ONLY or PREFER_JRE - regSearchWow(jreKeyName, FOUND_JRE); - if (jdkPreference != JRE_ONLY) { - regSearchWow(sdkKeyName, FOUND_SDK); - } - } -} - -BOOL findJavaHome(char* path, const int jdkPreference) { - regSearchJreSdk("SOFTWARE\\JavaSoft\\Java Runtime Environment", - "SOFTWARE\\JavaSoft\\Java Development Kit", - jdkPreference); - if (foundJava == NO_JAVA_FOUND) { - regSearchJreSdk("SOFTWARE\\IBM\\Java2 Runtime Environment", - "SOFTWARE\\IBM\\Java Development Kit", - jdkPreference); - } - if (foundJava != NO_JAVA_FOUND) { - HKEY hKey; - if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, - foundJavaKey, - 0, - KEY_READ | (foundJava & KEY_WOW64_64KEY), - &hKey) == ERROR_SUCCESS) { - unsigned char buffer[BIG_STR] = {0}; - unsigned long bufferlength = BIG_STR; - unsigned long datatype; - if (RegQueryValueEx(hKey, "JavaHome", NULL, &datatype, buffer, - &bufferlength) == ERROR_SUCCESS) { - int i = 0; - do { - path[i] = buffer[i]; - } while (path[i++] != 0); - // (foundJava & FOUND_SDK) { // removed by fry - // appendPath(path, "jre"); - // - RegCloseKey(hKey); - return TRUE; - } - RegCloseKey(hKey); - } - } - return FALSE; -} - -/* - * Extract the executable name, returns path length. - */ -int getExePath(char* exePath) { - if (GetModuleFileName(hModule, exePath, _MAX_PATH) == 0) { - return -1; - } - return strrchr(exePath, '\\') - exePath; -} - -void appendPath(char* basepath, const char* path) { - if (basepath[strlen(basepath) - 1] != '\\') { - strcat(basepath, "\\"); - } - strcat(basepath, path); -} - -void appendJavaw(char* jrePath) { - if (console) { - appendPath(jrePath, "bin\\java.exe"); - } else { - appendPath(jrePath, "bin\\javaw.exe"); - } -} - -void appendLauncher(const BOOL setProcName, char* exePath, - const int pathLen, char* cmd) { - if (setProcName) { - char tmpspec[_MAX_PATH]; - char tmpfile[_MAX_PATH]; - strcpy(tmpspec, cmd); - strcat(tmpspec, LAUNCH4J_TMP_DIR); - tmpspec[strlen(tmpspec) - 1] = 0; - if (_stat(tmpspec, &statBuf) == 0) { - // Remove temp launchers and manifests - struct _finddata_t c_file; - long hFile; - appendPath(tmpspec, "*.exe"); - strcpy(tmpfile, cmd); - strcat(tmpfile, LAUNCH4J_TMP_DIR); - char* filename = tmpfile + strlen(tmpfile); - if ((hFile = _findfirst(tmpspec, &c_file)) != -1L) { - do { - strcpy(filename, c_file.name); - debug("Unlink:\t\t%s\n", tmpfile); - _unlink(tmpfile); - strcat(tmpfile, MANIFEST); - debug("Unlink:\t\t%s\n", tmpfile); - _unlink(tmpfile); - } while (_findnext(hFile, &c_file) == 0); - } - _findclose(hFile); - } else { - if (_mkdir(tmpspec) != 0) { - debug("Mkdir failed:\t%s\n", tmpspec); - appendJavaw(cmd); - return; - } - } - char javaw[_MAX_PATH]; - strcpy(javaw, cmd); - appendJavaw(javaw); - strcpy(tmpfile, cmd); - strcat(tmpfile, LAUNCH4J_TMP_DIR); - char* tmpfilename = tmpfile + strlen(tmpfile); - char* exeFilePart = exePath + pathLen + 1; - - // Copy manifest - char manifest[_MAX_PATH] = {0}; - strcpy(manifest, exePath); - strcat(manifest, MANIFEST); - if (_stat(manifest, &statBuf) == 0) { - strcat(tmpfile, exeFilePart); - strcat(tmpfile, MANIFEST); - debug("Copy:\t\t%s -> %s\n", manifest, tmpfile); - CopyFile(manifest, tmpfile, FALSE); - } - - // Copy launcher - strcpy(tmpfilename, exeFilePart); - debug("Copy:\t\t%s -> %s\n", javaw, tmpfile); - if (CopyFile(javaw, tmpfile, FALSE)) { - strcpy(cmd, tmpfile); - return; - } else if (_stat(javaw, &statBuf) == 0) { - long fs = statBuf.st_size; - if (_stat(tmpfile, &statBuf) == 0 && fs == statBuf.st_size) { - debug("Reusing:\t\t%s\n", tmpfile); - strcpy(cmd, tmpfile); - return; - } - } - } - appendJavaw(cmd); -} - -void appendAppClasspath(char* dst, const char* src, const char* classpath) { - strcat(dst, src); - if (*classpath) { - strcat(dst, ";"); - } -} - -BOOL isJrePathOk(const char* path) { - char javaw[_MAX_PATH]; - BOOL result = FALSE; - if (*path) { - strcpy(javaw, path); - appendJavaw(javaw); - result = _stat(javaw, &statBuf) == 0; - } - debug("Check launcher:\t%s %s\n", javaw, result ? "(OK)" : "(n/a)"); - return result; -} - -/* - * Expand environment %variables% - */ -BOOL expandVars(char *dst, const char *src, const char *exePath, const int pathLen) { - char varName[STR]; - char varValue[MAX_VAR_SIZE]; - while (strlen(src) > 0) { - char *start = strchr(src, '%'); - if (start != NULL) { - char *end = strchr(start + 1, '%'); - if (end == NULL) { - return FALSE; - } - // Copy content up to %VAR% - strncat(dst, src, start - src); - // Insert value of %VAR% - *varName = 0; - strncat(varName, start + 1, end - start - 1); - // Remember value start for logging - char *varValue = dst + strlen(dst); - if (strcmp(varName, "EXEDIR") == 0) { - strncat(dst, exePath, pathLen); - } else if (strcmp(varName, "EXEFILE") == 0) { - strcat(dst, exePath); - } else if (strcmp(varName, "PWD") == 0) { - GetCurrentDirectory(_MAX_PATH, dst + strlen(dst)); - } else if (strcmp(varName, "OLDPWD") == 0) { - strcat(dst, oldPwd); - } else if (strstr(varName, HKEY_STR) == varName) { - regQueryValue(varName, dst + strlen(dst), BIG_STR); - } else if (GetEnvironmentVariable(varName, varValue, MAX_VAR_SIZE) > 0) { - strcat(dst, varValue); - } - debug("Substitute:\t%s = %s\n", varName, varValue); - src = end + 1; - } else { - // Copy remaining content - strcat(dst, src); - break; - } - } - return TRUE; -} - -void appendHeapSizes(char *dst) { - MEMORYSTATUS m; - memset(&m, 0, sizeof(m)); - GlobalMemoryStatus(&m); - - appendHeapSize(dst, INITIAL_HEAP_SIZE, INITIAL_HEAP_PERCENT, - m.dwAvailPhys, "-Xms"); - appendHeapSize(dst, MAX_HEAP_SIZE, MAX_HEAP_PERCENT, - m.dwAvailPhys, "-Xmx"); -} - -void appendHeapSize(char *dst, const int absID, const int percentID, - const DWORD freeMemory, const char *option) { - - const int mb = 1048576; // 1 MB - int abs = loadInt(absID); - int percent = loadInt(percentID); - int free = (long long) freeMemory * percent / (100 * mb); // 100% * 1 MB - int size = free > abs ? free : abs; - if (size > 0) { - debug("Heap %s:\t%d MB / %d%%, Free: %d MB, Heap size: %d MB\n", - option, abs, percent, freeMemory / mb, size); - strcat(dst, option); - _itoa(size, dst + strlen(dst), 10); // 10 -- radix - strcat(dst, "m "); - } -} - -int prepare(const char *lpCmdLine) { - char tmp[MAX_ARGS] = {0}; - hModule = GetModuleHandle(NULL); - if (hModule == NULL) { - return FALSE; - } - - // Get executable path - char exePath[_MAX_PATH] = {0}; - int pathLen = getExePath(exePath); - if (pathLen == -1) { - return FALSE; - } - - // Initialize logging - if (strstr(lpCmdLine, "--l4j-debug") != NULL) { - hLog = openLogFile(exePath, pathLen); - if (hLog == NULL) { - return FALSE; - } - debug("\n\nCmdLine:\t%s %s\n", exePath, lpCmdLine); - } - - setWow64Flag(); - - // Set default error message, title and optional support web site url. - loadString(SUPPORT_URL, errUrl); - loadString(ERR_TITLE, errTitle); - if (!loadString(STARTUP_ERR, errMsg)) { - return FALSE; - } - - // Single instance - loadString(MUTEX_NAME, mutexName); - if (*mutexName) { - SECURITY_ATTRIBUTES security; - security.nLength = sizeof(SECURITY_ATTRIBUTES); - security.bInheritHandle = TRUE; - security.lpSecurityDescriptor = NULL; - CreateMutexA(&security, FALSE, mutexName); - if (GetLastError() == ERROR_ALREADY_EXISTS) { - debug("Instance already exists."); - return ERROR_ALREADY_EXISTS; - } - } - - // Working dir - char tmp_path[_MAX_PATH] = {0}; - GetCurrentDirectory(_MAX_PATH, oldPwd); - if (loadString(CHDIR, tmp_path)) { - strncpy(workingDir, exePath, pathLen); - appendPath(workingDir, tmp_path); - _chdir(workingDir); - debug("Working dir:\t%s\n", workingDir); - } - - // Use bundled jre or find java - if (loadString(JRE_PATH, tmp_path)) { - char jrePath[MAX_ARGS] = {0}; - expandVars(jrePath, tmp_path, exePath, pathLen); - debug("Bundled JRE:\t%s\n", jrePath); - if (jrePath[0] == '\\' || jrePath[1] == ':') { - // Absolute - strcpy(cmd, jrePath); - } else { - // Relative - strncpy(cmd, exePath, pathLen); - appendPath(cmd, jrePath); - } - } - if (!isJrePathOk(cmd)) { - if (!loadString(JAVA_MIN_VER, javaMinVer)) { - loadString(BUNDLED_JRE_ERR, errMsg); - return FALSE; - } - loadString(JAVA_MAX_VER, javaMaxVer); - if (!findJavaHome(cmd, loadInt(JDK_PREFERENCE))) { - loadString(JRE_VERSION_ERR, errMsg); - strcat(errMsg, " "); - strcat(errMsg, javaMinVer); - if (*javaMaxVer) { - strcat(errMsg, " - "); - strcat(errMsg, javaMaxVer); - } - loadString(DOWNLOAD_URL, errUrl); - return FALSE; - } - if (!isJrePathOk(cmd)) { - loadString(LAUNCHER_ERR, errMsg); - return FALSE; - } - } - - // Append a path to the Path environment variable - char jreBinPath[_MAX_PATH]; - strcpy(jreBinPath, cmd); - strcat(jreBinPath, "\\bin"); - if (!appendToPathVar(jreBinPath)) { - return FALSE; - } - - // Set environment variables - char envVars[MAX_VAR_SIZE] = {0}; - loadString(ENV_VARIABLES, envVars); - char *var = strtok(envVars, "\t"); - while (var != NULL) { - char *varValue = strchr(var, '='); - *varValue++ = 0; - *tmp = 0; - expandVars(tmp, varValue, exePath, pathLen); - debug("Set var:\t%s = %s\n", var, tmp); - SetEnvironmentVariable(var, tmp); - var = strtok(NULL, "\t"); - } - *tmp = 0; - - // Process priority - priority = loadInt(PRIORITY_CLASS); - - // Custom process name - const BOOL setProcName = loadBool(SET_PROC_NAME) - && strstr(lpCmdLine, "--l4j-default-proc") == NULL; - const BOOL wrapper = loadBool(WRAPPER); - - char jdk_path[_MAX_PATH] = {0}; // fry - strcpy(jdk_path, cmd); - //msgBox(jdk_path); - - appendLauncher(setProcName, exePath, pathLen, cmd); - - // Heap sizes - appendHeapSizes(args); - - // JVM options - if (loadString(JVM_OPTIONS, tmp)) { - strcat(tmp, " "); - } else { - *tmp = 0; - } - /* - * Load additional JVM options from .l4j.ini file - * Options are separated by spaces or CRLF - * # starts an inline comment - */ - strncpy(tmp_path, exePath, strlen(exePath) - 3); - strcat(tmp_path, "l4j.ini"); - long hFile; - if ((hFile = _open(tmp_path, _O_RDONLY)) != -1) { - const int jvmOptLen = strlen(tmp); - char* src = tmp + jvmOptLen; - char* dst = src; - const int len = _read(hFile, src, MAX_ARGS - jvmOptLen - BIG_STR); - BOOL copy = TRUE; - int i; - for (i = 0; i < len; i++, src++) { - if (*src == '#') { - copy = FALSE; - } else if (*src == 13 || *src == 10) { - copy = TRUE; - if (dst > tmp && *(dst - 1) != ' ') { - *dst++ = ' '; - } - } else if (copy) { - *dst++ = *src; - } - } - *dst = 0; - if (len > 0 && *(dst - 1) != ' ') { - strcat(tmp, " "); - } - _close(hFile); - } - - // Expand environment %variables% - expandVars(args, tmp, exePath, pathLen); - - // MainClass + Classpath or Jar - char mainClass[STR] = {0}; - char jar[_MAX_PATH] = {0}; - loadString(JAR, jar); - if (loadString(MAIN_CLASS, mainClass)) { - if (!loadString(CLASSPATH, tmp)) { - return FALSE; - } - char exp[MAX_ARGS] = {0}; - expandVars(exp, tmp, exePath, pathLen); - strcat(args, "-classpath \""); - if (wrapper) { - appendAppClasspath(args, exePath, exp); - } else if (*jar) { - appendAppClasspath(args, jar, exp); - } - - // add tools.jar for JDK [fry] - char tools[_MAX_PATH] = { 0 }; - sprintf(tools, "%s\\lib\\tools.jar", jdk_path); - appendAppClasspath(args, tools, exp); - - // Deal with wildcards or >> strcat(args, exp); << - char* cp = strtok(exp, ";"); - while(cp != NULL) { - debug("Add classpath:\t%s\n", cp); - if (strpbrk(cp, "*?") != NULL) { - int len = strrchr(cp, '\\') - cp + 1; - strncpy(tmp_path, cp, len); - char* filename = tmp_path + len; - *filename = 0; - struct _finddata_t c_file; - long hFile; - if ((hFile = _findfirst(cp, &c_file)) != -1L) { - do { - strcpy(filename, c_file.name); - strcat(args, tmp_path); - strcat(args, ";"); - debug(" \" :\t%s\n", tmp_path); - } while (_findnext(hFile, &c_file) == 0); - } - _findclose(hFile); - } else { - strcat(args, cp); - strcat(args, ";"); - } - cp = strtok(NULL, ";"); - } - *(args + strlen(args) - 1) = 0; - - strcat(args, "\" "); - strcat(args, mainClass); - } else if (wrapper) { - strcat(args, "-jar \""); - strcat(args, exePath); - strcat(args, "\""); - } else { - strcat(args, "-jar \""); - strncat(args, exePath, pathLen); - appendPath(args, jar); - strcat(args, "\""); - } - - // Constant command line args - if (loadString(CMD_LINE, tmp)) { - strcat(args, " "); - strcat(args, tmp); - } - - // Command line args - if (*lpCmdLine) { - strcpy(tmp, lpCmdLine); - char* dst; - while ((dst = strstr(tmp, "--l4j-")) != NULL) { - char* src = strchr(dst, ' '); - if (src == NULL || *(src + 1) == 0) { - *dst = 0; - } else { - strcpy(dst, src + 1); - } - } - if (*tmp) { - strcat(args, " "); - strcat(args, tmp); - } - } - - debug("Launcher:\t%s\n", cmd); - debug("Launcher args:\t%s\n", args); - debug("Args length:\t%d/32768 chars\n", strlen(args)); - return TRUE; -} - -void closeHandles() { - CloseHandle(pi.hThread); - CloseHandle(pi.hProcess); - closeLogFile(); -} - -/* - * Append a path to the Path environment variable - */ -BOOL appendToPathVar(const char* path) { - char chBuf[MAX_VAR_SIZE] = {0}; - - const int pathSize = GetEnvironmentVariable("Path", chBuf, MAX_VAR_SIZE); - if (MAX_VAR_SIZE - pathSize - 1 < strlen(path)) { - return FALSE; - } - strcat(chBuf, ";"); - strcat(chBuf, path); - return SetEnvironmentVariable("Path", chBuf); -} - -// may need to ignore STILL_ACTIVE (error code 259) here -// http://msdn.microsoft.com/en-us/library/ms683189(VS.85).aspx -DWORD execute(const BOOL wait) { - STARTUPINFO si; - memset(&pi, 0, sizeof(pi)); - memset(&si, 0, sizeof(si)); - si.cb = sizeof(si); - - DWORD dwExitCode = -1; - char cmdline[MAX_ARGS]; - strcpy(cmdline, "\""); - strcat(cmdline, cmd); - strcat(cmdline, "\" "); - strcat(cmdline, args); - if (CreateProcess(NULL, cmdline, NULL, NULL, - TRUE, priority, NULL, NULL, &si, &pi)) { - if (wait) { - WaitForSingleObject(pi.hProcess, INFINITE); - GetExitCodeProcess(pi.hProcess, &dwExitCode); - debug("Exit code:\t%d\n", dwExitCode); - closeHandles(); - } else { - dwExitCode = 0; - } - } - return dwExitCode; -} diff --git a/build/windows/launcher/launch4j/head_src/head.h b/build/windows/launcher/launch4j/head_src/head.h deleted file mode 100755 index 2e3bdb1d093..00000000000 --- a/build/windows/launcher/launch4j/head_src/head.h +++ /dev/null @@ -1,113 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2008 Grzegorz Kowal, - Ian Roberts (jdk preference patch) - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - Except as contained in this notice, the name(s) of the above copyright holders - shall not be used in advertising or otherwise to promote the sale, use or other - dealings in this Software without prior written authorization. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -#ifndef _LAUNCH4J_HEAD__INCLUDED_ -#define _LAUNCH4J_HEAD__INCLUDED_ - -#define WIN32_LEAN_AND_MEAN // VC - Exclude rarely-used stuff from Windows headers - -// Windows Header Files: -#include - -// C RunTime Header Files -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define NO_JAVA_FOUND 0 -#define FOUND_JRE 1 -#define FOUND_SDK 2 - -#define JRE_ONLY 0 -#define PREFER_JRE 1 -#define PREFER_JDK 2 -#define JDK_ONLY 3 - -#define LAUNCH4J_TMP_DIR "\\launch4j-tmp\\" -#define MANIFEST ".manifest" - -#define KEY_WOW64_64KEY 0x0100 - -#define HKEY_STR "HKEY" -#define HKEY_CLASSES_ROOT_STR "HKEY_CLASSES_ROOT" -#define HKEY_CURRENT_USER_STR "HKEY_CURRENT_USER" -#define HKEY_LOCAL_MACHINE_STR "HKEY_LOCAL_MACHINE" -#define HKEY_USERS_STR "HKEY_USERS" -#define HKEY_CURRENT_CONFIG_STR "HKEY_CURRENT_CONFIG" - -#define STR 128 -#define BIG_STR 1024 -#define MAX_VAR_SIZE 32767 -#define MAX_ARGS 32768 - -#define TRUE_STR "true" -#define FALSE_STR "false" - -#define debug(args...) if (hLog != NULL) fprintf(hLog, ## args); - -typedef void (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL); - -FILE* openLogFile(const char* exePath, const int pathLen); -void closeLogFile(); -void msgBox(const char* text); -void signalError(); -BOOL loadString(const int resID, char* buffer); -BOOL loadBool(const int resID); -int loadInt(const int resID); -BOOL regQueryValue(const char* regPath, unsigned char* buffer, - unsigned long bufferLength); -void regSearch(const HKEY hKey, const char* keyName, const int searchType); -void regSearchWow(const char* keyName, const int searchType); -void regSearchJreSdk(const char* jreKeyName, const char* sdkKeyName, - const int jdkPreference); -BOOL findJavaHome(char* path, const int jdkPreference); -int getExePath(char* exePath); -void appendPath(char* basepath, const char* path); -void appendJavaw(char* jrePath); -void appendAppClasspath(char* dst, const char* src, const char* classpath); -BOOL isJrePathOk(const char* path); -BOOL expandVars(char *dst, const char *src, const char *exePath, const int pathLen); -void appendHeapSizes(char *dst); -void appendHeapSize(char *dst, const int absID, const int percentID, - const DWORD freeMemory, const char *option); -int prepare(const char *lpCmdLine); -void closeHandles(); -BOOL appendToPathVar(const char* path); -DWORD execute(const BOOL wait); - -#endif // _LAUNCH4J_HEAD__INCLUDED_ diff --git a/build/windows/launcher/launch4j/head_src/resource.h b/build/windows/launcher/launch4j/head_src/resource.h deleted file mode 100755 index 3c0f73cfc0b..00000000000 --- a/build/windows/launcher/launch4j/head_src/resource.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2008 Grzegorz Kowal - Ian Roberts (jdk preference patch) - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - Except as contained in this notice, the name(s) of the above copyright holders - shall not be used in advertising or otherwise to promote the sale, use or other - dealings in this Software without prior written authorization. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -// ICON -#define APP_ICON 1 - -// BITMAP -#define SPLASH_BITMAP 1 - -// RCDATA -#define JRE_PATH 1 -#define JAVA_MIN_VER 2 -#define JAVA_MAX_VER 3 -#define SHOW_SPLASH 4 -#define SPLASH_WAITS_FOR_WINDOW 5 -#define SPLASH_TIMEOUT 6 -#define SPLASH_TIMEOUT_ERR 7 -#define CHDIR 8 -#define SET_PROC_NAME 9 -#define ERR_TITLE 10 -#define GUI_HEADER_STAYS_ALIVE 11 -#define JVM_OPTIONS 12 -#define CMD_LINE 13 -#define JAR 14 -#define MAIN_CLASS 15 -#define CLASSPATH 16 -#define WRAPPER 17 -#define JDK_PREFERENCE 18 -#define ENV_VARIABLES 19 -#define PRIORITY_CLASS 20 -#define DOWNLOAD_URL 21 -#define SUPPORT_URL 22 -#define MUTEX_NAME 23 -#define INSTANCE_WINDOW_TITLE 24 -#define INITIAL_HEAP_SIZE 25 -#define INITIAL_HEAP_PERCENT 26 -#define MAX_HEAP_SIZE 27 -#define MAX_HEAP_PERCENT 28 - -#define STARTUP_ERR 101 -#define BUNDLED_JRE_ERR 102 -#define JRE_VERSION_ERR 103 -#define LAUNCHER_ERR 104 -#define INSTANCE_ALREADY_EXISTS_MSG 105 diff --git a/build/windows/launcher/launch4j/launch4j.exe b/build/windows/launcher/launch4j/launch4j.exe deleted file mode 100755 index 0e2eb2ba594..00000000000 Binary files a/build/windows/launcher/launch4j/launch4j.exe and /dev/null differ diff --git a/build/windows/launcher/launch4j/launch4j.jar b/build/windows/launcher/launch4j/launch4j.jar deleted file mode 100755 index ec68ae48dd9..00000000000 Binary files a/build/windows/launcher/launch4j/launch4j.jar and /dev/null differ diff --git a/build/windows/launcher/launch4j/launch4j.jfpr b/build/windows/launcher/launch4j/launch4j.jfpr deleted file mode 100755 index a2e63ebc520..00000000000 Binary files a/build/windows/launcher/launch4j/launch4j.jfpr and /dev/null differ diff --git a/build/windows/launcher/launch4j/launch4jc.exe b/build/windows/launcher/launch4j/launch4jc.exe deleted file mode 100755 index 565cc2f07c1..00000000000 Binary files a/build/windows/launcher/launch4j/launch4jc.exe and /dev/null differ diff --git a/build/windows/launcher/launch4j/lib/JGoodies.Forms.LICENSE.txt b/build/windows/launcher/launch4j/lib/JGoodies.Forms.LICENSE.txt deleted file mode 100755 index 9ba2419e7fd..00000000000 --- a/build/windows/launcher/launch4j/lib/JGoodies.Forms.LICENSE.txt +++ /dev/null @@ -1,31 +0,0 @@ - - The BSD License for the JGoodies Forms - ====================================== - -Copyright (c) 2002-2004 JGoodies Karsten Lentzsch. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - o Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - o Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - o Neither the name of JGoodies Karsten Lentzsch nor the names of - its contributors may be used to endorse or promote products derived - from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; -OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, -EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/build/windows/launcher/launch4j/lib/JGoodies.Looks.LICENSE.txt b/build/windows/launcher/launch4j/lib/JGoodies.Looks.LICENSE.txt deleted file mode 100755 index 8bbefa2ebd6..00000000000 --- a/build/windows/launcher/launch4j/lib/JGoodies.Looks.LICENSE.txt +++ /dev/null @@ -1,31 +0,0 @@ - - The BSD License for the JGoodies Looks - ====================================== - -Copyright (c) 2001-2007 JGoodies Karsten Lentzsch. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - o Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - o Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - o Neither the name of JGoodies Karsten Lentzsch nor the names of - its contributors may be used to endorse or promote products derived - from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; -OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, -EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/build/windows/launcher/launch4j/lib/XStream.LICENSE.txt b/build/windows/launcher/launch4j/lib/XStream.LICENSE.txt deleted file mode 100755 index 5ccad869400..00000000000 --- a/build/windows/launcher/launch4j/lib/XStream.LICENSE.txt +++ /dev/null @@ -1,27 +0,0 @@ -(BSD Style License) - -Copyright (c) 2003-2004, Joe Walnes -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list of -conditions and the following disclaimer. Redistributions in binary form must reproduce -the above copyright notice, this list of conditions and the following disclaimer in -the documentation and/or other materials provided with the distribution. - -Neither the name of XStream nor the names of its contributors may be used to endorse -or promote products derived from this software without specific prior written -permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY -EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES -OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT -SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY -WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -DAMAGE. diff --git a/build/windows/launcher/launch4j/lib/commons-beanutils.jar b/build/windows/launcher/launch4j/lib/commons-beanutils.jar deleted file mode 100755 index b1b89c9c921..00000000000 Binary files a/build/windows/launcher/launch4j/lib/commons-beanutils.jar and /dev/null differ diff --git a/build/windows/launcher/launch4j/lib/commons-logging.jar b/build/windows/launcher/launch4j/lib/commons-logging.jar deleted file mode 100755 index b73a80fab64..00000000000 Binary files a/build/windows/launcher/launch4j/lib/commons-logging.jar and /dev/null differ diff --git a/build/windows/launcher/launch4j/lib/commons.LICENSE.txt b/build/windows/launcher/launch4j/lib/commons.LICENSE.txt deleted file mode 100755 index fdb6475220a..00000000000 --- a/build/windows/launcher/launch4j/lib/commons.LICENSE.txt +++ /dev/null @@ -1,50 +0,0 @@ -/* - - ============================================================================ - The Apache Software License, Version 1.1 - ============================================================================ - - Copyright (C) @year@ The Apache Software Foundation. All rights reserved. - - Redistribution and use in source and binary forms, with or without modifica- - tion, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - 3. The end-user documentation included with the redistribution, if any, must - include the following acknowledgment: "This product includes software - developed by the Apache Software Foundation (http://www.apache.org/)." - Alternately, this acknowledgment may appear in the software itself, if - and wherever such third-party acknowledgments normally appear. - - 4. The names "Apache Cocoon" and "Apache Software Foundation" must not be - used to endorse or promote products derived from this software without - prior written permission. For written permission, please contact - apache@apache.org. - - 5. Products derived from this software may not be called "Apache", nor may - "Apache" appear in their name, without prior written permission of the - Apache Software Foundation. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU- - DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS - OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - This software consists of voluntary contributions made by many individuals - on behalf of the Apache Software Foundation and was originally created by - Stefano Mazzocchi . For more information on the Apache - Software Foundation, please see . - -*/ diff --git a/build/windows/launcher/launch4j/lib/forms.jar b/build/windows/launcher/launch4j/lib/forms.jar deleted file mode 100755 index aed060a49bf..00000000000 Binary files a/build/windows/launcher/launch4j/lib/forms.jar and /dev/null differ diff --git a/build/windows/launcher/launch4j/lib/formsrt.jar b/build/windows/launcher/launch4j/lib/formsrt.jar deleted file mode 100755 index e0de6ecf1f5..00000000000 Binary files a/build/windows/launcher/launch4j/lib/formsrt.jar and /dev/null differ diff --git a/build/windows/launcher/launch4j/lib/foxtrot.LICENSE.txt b/build/windows/launcher/launch4j/lib/foxtrot.LICENSE.txt deleted file mode 100755 index 5fa4019d5bf..00000000000 --- a/build/windows/launcher/launch4j/lib/foxtrot.LICENSE.txt +++ /dev/null @@ -1,25 +0,0 @@ -Copyright (c) 2002, Simone Bordet & Marco Cravero -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted -provided that the following conditions are met: - - - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - - Neither the name of Foxtrot nor the names of the contributors may be used - to endorse or promote products derived from this software without specific prior - written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS -OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS -BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, -OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF -THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/build/windows/launcher/launch4j/lib/foxtrot.jar b/build/windows/launcher/launch4j/lib/foxtrot.jar deleted file mode 100755 index f39103a0909..00000000000 Binary files a/build/windows/launcher/launch4j/lib/foxtrot.jar and /dev/null differ diff --git a/build/windows/launcher/launch4j/lib/looks.jar b/build/windows/launcher/launch4j/lib/looks.jar deleted file mode 100755 index d2c47c743f4..00000000000 Binary files a/build/windows/launcher/launch4j/lib/looks.jar and /dev/null differ diff --git a/build/windows/launcher/launch4j/lib/xstream.jar b/build/windows/launcher/launch4j/lib/xstream.jar deleted file mode 100755 index 392e1c93739..00000000000 Binary files a/build/windows/launcher/launch4j/lib/xstream.jar and /dev/null differ diff --git a/build/windows/launcher/launch4j/manifest/uac.exe.manifest b/build/windows/launcher/launch4j/manifest/uac.exe.manifest deleted file mode 100755 index 3041fbc5b10..00000000000 --- a/build/windows/launcher/launch4j/manifest/uac.exe.manifest +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/build/windows/launcher/launch4j/manifest/xp-themes.exe.manifest b/build/windows/launcher/launch4j/manifest/xp-themes.exe.manifest deleted file mode 100755 index e2c7511f9ea..00000000000 --- a/build/windows/launcher/launch4j/manifest/xp-themes.exe.manifest +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/build/windows/launcher/launch4j/src/images/asterix-o.gif b/build/windows/launcher/launch4j/src/images/asterix-o.gif deleted file mode 100755 index f5cf3b3072a..00000000000 Binary files a/build/windows/launcher/launch4j/src/images/asterix-o.gif and /dev/null differ diff --git a/build/windows/launcher/launch4j/src/images/asterix.gif b/build/windows/launcher/launch4j/src/images/asterix.gif deleted file mode 100755 index ba801670aa9..00000000000 Binary files a/build/windows/launcher/launch4j/src/images/asterix.gif and /dev/null differ diff --git a/build/windows/launcher/launch4j/src/images/build.png b/build/windows/launcher/launch4j/src/images/build.png deleted file mode 100755 index 625285f0bb6..00000000000 Binary files a/build/windows/launcher/launch4j/src/images/build.png and /dev/null differ diff --git a/build/windows/launcher/launch4j/src/images/button_ok.png b/build/windows/launcher/launch4j/src/images/button_ok.png deleted file mode 100755 index 5b0f6a6174f..00000000000 Binary files a/build/windows/launcher/launch4j/src/images/button_ok.png and /dev/null differ diff --git a/build/windows/launcher/launch4j/src/images/cancel16.png b/build/windows/launcher/launch4j/src/images/cancel16.png deleted file mode 100755 index a432b492c4f..00000000000 Binary files a/build/windows/launcher/launch4j/src/images/cancel16.png and /dev/null differ diff --git a/build/windows/launcher/launch4j/src/images/down16.png b/build/windows/launcher/launch4j/src/images/down16.png deleted file mode 100755 index f3bc4cd0932..00000000000 Binary files a/build/windows/launcher/launch4j/src/images/down16.png and /dev/null differ diff --git a/build/windows/launcher/launch4j/src/images/edit_add16.png b/build/windows/launcher/launch4j/src/images/edit_add16.png deleted file mode 100755 index e9485082eaa..00000000000 Binary files a/build/windows/launcher/launch4j/src/images/edit_add16.png and /dev/null differ diff --git a/build/windows/launcher/launch4j/src/images/info.png b/build/windows/launcher/launch4j/src/images/info.png deleted file mode 100755 index eb37d9a08ca..00000000000 Binary files a/build/windows/launcher/launch4j/src/images/info.png and /dev/null differ diff --git a/build/windows/launcher/launch4j/src/images/new.png b/build/windows/launcher/launch4j/src/images/new.png deleted file mode 100755 index 6e2700ad915..00000000000 Binary files a/build/windows/launcher/launch4j/src/images/new.png and /dev/null differ diff --git a/build/windows/launcher/launch4j/src/images/new16.png b/build/windows/launcher/launch4j/src/images/new16.png deleted file mode 100755 index f38d02ee599..00000000000 Binary files a/build/windows/launcher/launch4j/src/images/new16.png and /dev/null differ diff --git a/build/windows/launcher/launch4j/src/images/ok16.png b/build/windows/launcher/launch4j/src/images/ok16.png deleted file mode 100755 index 5b0f6a6174f..00000000000 Binary files a/build/windows/launcher/launch4j/src/images/ok16.png and /dev/null differ diff --git a/build/windows/launcher/launch4j/src/images/open.png b/build/windows/launcher/launch4j/src/images/open.png deleted file mode 100755 index a801665fd57..00000000000 Binary files a/build/windows/launcher/launch4j/src/images/open.png and /dev/null differ diff --git a/build/windows/launcher/launch4j/src/images/open16.png b/build/windows/launcher/launch4j/src/images/open16.png deleted file mode 100755 index 5321c17c63f..00000000000 Binary files a/build/windows/launcher/launch4j/src/images/open16.png and /dev/null differ diff --git a/build/windows/launcher/launch4j/src/images/run.png b/build/windows/launcher/launch4j/src/images/run.png deleted file mode 100755 index b41fa2b975b..00000000000 Binary files a/build/windows/launcher/launch4j/src/images/run.png and /dev/null differ diff --git a/build/windows/launcher/launch4j/src/images/save.png b/build/windows/launcher/launch4j/src/images/save.png deleted file mode 100755 index 74b37b0b510..00000000000 Binary files a/build/windows/launcher/launch4j/src/images/save.png and /dev/null differ diff --git a/build/windows/launcher/launch4j/src/images/up16.png b/build/windows/launcher/launch4j/src/images/up16.png deleted file mode 100755 index 184c118b634..00000000000 Binary files a/build/windows/launcher/launch4j/src/images/up16.png and /dev/null differ diff --git a/build/windows/launcher/launch4j/src/launch4j.properties b/build/windows/launcher/launch4j/src/launch4j.properties deleted file mode 100755 index 463c7a034af..00000000000 --- a/build/windows/launcher/launch4j/src/launch4j.properties +++ /dev/null @@ -1,2 +0,0 @@ -versionNumber=3.0.1.0 -version=3.0.1 diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/Builder.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/Builder.java deleted file mode 100755 index d7badc7f3e4..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/Builder.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on 2005-04-24 - */ -package net.sf.launch4j; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.StringTokenizer; - -import net.sf.launch4j.binding.InvariantViolationException; -import net.sf.launch4j.config.Config; -import net.sf.launch4j.config.ConfigPersister; - -/** - * @author Copyright (C) 2005 Grzegorz Kowal - */ -public class Builder { - private final Log _log; - private final File _basedir; - - public Builder(Log log) { - _log = log; - _basedir = Util.getJarBasedir(); - } - - public Builder(Log log, File basedir) { - _log = log; - _basedir = basedir; - } - - /** - * @return Output file path. - */ - public File build() throws BuilderException { - final Config c = ConfigPersister.getInstance().getConfig(); - try { - c.validate(); - } catch (InvariantViolationException e) { - throw new BuilderException(e.getMessage()); - } - File rc = null; - File ro = null; - File outfile = null; - FileInputStream is = null; - FileOutputStream os = null; - final RcBuilder rcb = new RcBuilder(); - try { - rc = rcb.build(c); - ro = Util.createTempFile("o"); - outfile = ConfigPersister.getInstance().getOutputFile(); - - Cmd resCmd = new Cmd(_basedir); - resCmd.addExe("windres") - .add(Util.WINDOWS_OS ? "--preprocessor=type" : "--preprocessor=cat") - .add("-J rc -O coff -F pe-i386") - .addAbsFile(rc) - .addAbsFile(ro); - _log.append(Messages.getString("Builder.compiling.resources")); - resCmd.exec(_log); - - Cmd ldCmd = new Cmd(_basedir); - ldCmd.addExe("ld") - .add("-mi386pe") - .add("--oformat pei-i386") - .add((c.getHeaderType().equals(Config.GUI_HEADER)) - ? "--subsystem windows" : "--subsystem console") - .add("-s") // strip symbols - .addFiles(c.getHeaderObjects()) - .addAbsFile(ro) - .addFiles(c.getLibs()) - .add("-o") - .addAbsFile(outfile); - _log.append(Messages.getString("Builder.linking")); - ldCmd.exec(_log); - - if (!c.isDontWrapJar()) { - _log.append(Messages.getString("Builder.wrapping")); - int len; - byte[] buffer = new byte[1024]; - is = new FileInputStream(Util.getAbsoluteFile( - ConfigPersister.getInstance().getConfigPath(), c.getJar())); - os = new FileOutputStream(outfile, true); - while ((len = is.read(buffer)) > 0) { - os.write(buffer, 0, len); - } - } - _log.append(Messages.getString("Builder.success") + outfile.getPath()); - return outfile; - } catch (IOException e) { - Util.delete(outfile); - _log.append(e.getMessage()); - throw new BuilderException(e); - } catch (ExecException e) { - Util.delete(outfile); - String msg = e.getMessage(); - if (msg != null && msg.indexOf("windres") != -1) { - if (e.getErrLine() != -1) { - _log.append(Messages.getString("Builder.line.has.errors", - String.valueOf(e.getErrLine()))); - _log.append(rcb.getLine(e.getErrLine())); - } else { - _log.append(Messages.getString("Builder.generated.resource.file")); - _log.append(rcb.getContent()); - } - } - throw new BuilderException(e); - } finally { - Util.close(is); - Util.close(os); - Util.delete(rc); - Util.delete(ro); - } - } -} - -class Cmd { - private final List _cmd = new ArrayList(); - private final File _basedir; - private final File _bindir; - - public Cmd(File basedir) { - _basedir = basedir; - String path = System.getProperty("launch4j.bindir"); - if (path == null) { - _bindir = new File(basedir, "bin"); - } else { - File bindir = new File(path); - _bindir = bindir.isAbsolute() ? bindir : new File(basedir, path); - } - } - - public Cmd add(String s) { - StringTokenizer st = new StringTokenizer(s); - while (st.hasMoreTokens()) { - _cmd.add(st.nextToken()); - } - return this; - } - - public Cmd addAbsFile(File file) { - _cmd.add(file.getPath()); - return this; - } - - public Cmd addFile(String pathname) { - _cmd.add(new File(_basedir, pathname).getPath()); - return this; - } - - public Cmd addExe(String pathname) { - if (Util.WINDOWS_OS) { - pathname += ".exe"; - } - _cmd.add(new File(_bindir, pathname).getPath()); - return this; - } - - public Cmd addFiles(List files) { - for (Iterator iter = files.iterator(); iter.hasNext();) { - addFile((String) iter.next()); - } - return this; - } - - public void exec(Log log) throws ExecException { - String[] cmd = (String[]) _cmd.toArray(new String[_cmd.size()]); - Util.exec(cmd, log); - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/BuilderException.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/BuilderException.java deleted file mode 100755 index a84c2e279bb..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/BuilderException.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on May 13, 2005 - */ -package net.sf.launch4j; - -/** - * @author Copyright (C) 2005 Grzegorz Kowal - */ -public class BuilderException extends Exception { - public BuilderException() {} - - public BuilderException(Throwable t) { - super(t); - } - - public BuilderException(String msg) { - super(msg); - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/ExecException.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/ExecException.java deleted file mode 100755 index 236ae780f15..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/ExecException.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on May 14, 2005 - */ -package net.sf.launch4j; - -/** - * @author Copyright (C) 2005 Grzegorz Kowal - */ -public class ExecException extends Exception { - private final int _errLine; - - public ExecException(Throwable t, int errLine) { - super(t); - _errLine = errLine; - } - - public ExecException(Throwable t) { - this(t, -1); - } - - public ExecException(String msg, int errLine) { - super(msg); - _errLine = errLine; - } - - public ExecException(String msg) { - this(msg, -1); - } - - public int getErrLine() { - return _errLine; - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/FileChooserFilter.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/FileChooserFilter.java deleted file mode 100755 index 5199a6deb3a..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/FileChooserFilter.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on 2004-01-15 - */ -package net.sf.launch4j; - -import java.io.File; - -import javax.swing.filechooser.FileFilter; - -/** - * @author Copyright (C) 2004 Grzegorz Kowal - */ -public class FileChooserFilter extends FileFilter { - String _description; - String[] _extensions; - - public FileChooserFilter(String description, String extension) { - _description = description; - _extensions = new String[] {extension}; - } - - public FileChooserFilter(String description, String[] extensions) { - _description = description; - _extensions = extensions; - } - - public boolean accept(File f) { - if (f.isDirectory()) { - return true; - } - String ext = Util.getExtension(f); - for (int i = 0; i < _extensions.length; i++) { - if (ext.toLowerCase().equals(_extensions[i].toLowerCase())) { - return true; - } - } - return false; - } - - public String getDescription() { - return _description; - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/Log.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/Log.java deleted file mode 100755 index c4d591b0cbb..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/Log.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on May 12, 2005 - */ -package net.sf.launch4j; - -import javax.swing.JTextArea; -import javax.swing.SwingUtilities; - -/** - * @author Copyright (C) 2005 Grzegorz Kowal - */ -public abstract class Log { - private static final Log _consoleLog = new ConsoleLog(); - private static final Log _antLog = new AntLog(); - - public abstract void clear(); - public abstract void append(String line); - - public static Log getConsoleLog() { - return _consoleLog; - } - - public static Log getAntLog() { - return _antLog; - } - - public static Log getSwingLog(JTextArea textArea) { - return new SwingLog(textArea); - } -} - -class ConsoleLog extends Log { - public void clear() { - System.out.println("\n"); - } - - public void append(String line) { - System.out.println("launch4j: " + line); - } -} - -class AntLog extends Log { - public void clear() { - System.out.println("\n"); - } - - public void append(String line) { - System.out.println(line); - } -} - -class SwingLog extends Log { - private final JTextArea _textArea; - - public SwingLog(JTextArea textArea) { - _textArea = textArea; - } - - public void clear() { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - _textArea.setText(""); - }}); - } - - public void append(final String line) { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - _textArea.append(line + "\n"); - }}); - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/Main.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/Main.java deleted file mode 100755 index 45f84ad7964..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/Main.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2008 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on Apr 21, 2005 - */ -package net.sf.launch4j; - -import java.io.File; -import java.io.InputStream; -import java.util.Properties; - -import net.sf.launch4j.config.ConfigPersister; -import net.sf.launch4j.formimpl.MainFrame; - -/** - * @author Copyright (C) 2005 Grzegorz Kowal - */ -public class Main { - private static String _name; - private static String _description; - - public static void main(String[] args) { - try { - Properties props = new Properties(); - InputStream in = Main.class.getClassLoader() - .getResourceAsStream("launch4j.properties"); - props.load(in); - in.close(); - setDescription(props); - - if (args.length == 0) { - ConfigPersister.getInstance().createBlank(); - MainFrame.createInstance(); - } else if (args.length == 1 && !args[0].startsWith("-")) { - ConfigPersister.getInstance().load(new File(args[0])); - Builder b = new Builder(Log.getConsoleLog()); - b.build(); - } else { - System.out.println(_description - + Messages.getString("Main.usage") - + ": launch4j config.xml"); - } - } catch (Exception e) { - Log.getConsoleLog().append(e.getMessage()); - } - } - - public static String getName() { - return _name; - } - - public static String getDescription() { - return _description; - } - - private static void setDescription(Properties props) { - _name = "Launch4j " + props.getProperty("version"); - _description = _name + - " (http://launch4j.sourceforge.net/)\n" + - "Cross-platform Java application wrapper" + - " for creating Windows native executables.\n\n" + - "Copyright (C) 2004, 2008 Grzegorz Kowal\n\n" + - "Launch4j comes with ABSOLUTELY NO WARRANTY.\n" + - "This is free software, licensed under the BSD License.\n" + - "This product includes software developed by the Apache Software Foundation" + - " (http://www.apache.org/)."; - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/Messages.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/Messages.java deleted file mode 100755 index 35d4c895084..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/Messages.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -package net.sf.launch4j; - -import java.text.MessageFormat; -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -public class Messages { - private static final String BUNDLE_NAME = "net.sf.launch4j.messages"; - - private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle - .getBundle(BUNDLE_NAME); - private static final MessageFormat FORMATTER = new MessageFormat(""); - - private Messages() { - } - - public static String getString(String key) { - try { - return RESOURCE_BUNDLE.getString(key); - } catch (MissingResourceException e) { - return '!' + key + '!'; - } - } - - public static String getString(String key, String arg0) { - return getString(key, new Object[] {arg0}); - } - - public static String getString(String key, String arg0, String arg1) { - return getString(key, new Object[] {arg0, arg1}); - } - - public static String getString(String key, String arg0, String arg1, String arg2) { - return getString(key, new Object[] {arg0, arg1, arg2}); - } - - public static String getString(String key, Object[] args) { - try { - FORMATTER.applyPattern(RESOURCE_BUNDLE.getString(key)); - return FORMATTER.format(args); - } catch (MissingResourceException e) { - return '!' + key + '!'; - } - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/OptionParser.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/OptionParser.java deleted file mode 100755 index bb2432c8e18..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/OptionParser.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on 2005-04-24 - */ -package net.sf.launch4j; - -//import net.sf.launch4j.config.Config; - -//import org.apache.commons.cli.CommandLine; -//import org.apache.commons.cli.CommandLineParser; -//import org.apache.commons.cli.HelpFormatter; -//import org.apache.commons.cli.Options; -//import org.apache.commons.cli.ParseException; -//import org.apache.commons.cli.PosixParser; - -/** - * @author Copyright (C) 2005 Grzegorz Kowal - */ -public class OptionParser { - -// private final Options _options; -// -// public OptionParser() { -// _options = new Options(); -// _options.addOption("h", "header", true, "header"); -// } -// -// public Config parse(Config c, String[] args) throws ParseException { -// CommandLineParser parser = new PosixParser(); -// CommandLine cl = parser.parse(_options, args); -// c.setJar(getFile(props, Config.JAR)); -// c.setOutfile(getFile(props, Config.OUTFILE)); -// } -// -// public void printHelp() { -// HelpFormatter formatter = new HelpFormatter(); -// formatter.printHelp("launch4j", _options); -// } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/RcBuilder.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/RcBuilder.java deleted file mode 100755 index f8885e3e6d4..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/RcBuilder.java +++ /dev/null @@ -1,340 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on 2005-04-24 - */ -package net.sf.launch4j; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.util.List; - -import net.sf.launch4j.config.Config; -import net.sf.launch4j.config.ConfigPersister; -import net.sf.launch4j.config.Jre; -import net.sf.launch4j.config.Msg; -import net.sf.launch4j.config.Splash; -import net.sf.launch4j.config.VersionInfo; - -/** - * @author Copyright (C) 2005 Grzegorz Kowal - */ -public class RcBuilder { - - // winnt.h - public static final int LANG_NEUTRAL = 0; - public static final int SUBLANG_NEUTRAL = 0; - public static final int SUBLANG_DEFAULT = 1; - public static final int SUBLANG_SYS_DEFAULT = 2; - - // MANIFEST - public static final int MANIFEST = 1; - - // ICON - public static final int APP_ICON = 1; - - // BITMAP - public static final int SPLASH_BITMAP = 1; - - // RCDATA - public static final int JRE_PATH = 1; - public static final int JAVA_MIN_VER = 2; - public static final int JAVA_MAX_VER = 3; - public static final int SHOW_SPLASH = 4; - public static final int SPLASH_WAITS_FOR_WINDOW = 5; - public static final int SPLASH_TIMEOUT = 6; - public static final int SPLASH_TIMEOUT_ERR = 7; - public static final int CHDIR = 8; - public static final int SET_PROC_NAME = 9; - public static final int ERR_TITLE = 10; - public static final int GUI_HEADER_STAYS_ALIVE = 11; - public static final int JVM_OPTIONS = 12; - public static final int CMD_LINE = 13; - public static final int JAR = 14; - public static final int MAIN_CLASS = 15; - public static final int CLASSPATH = 16; - public static final int WRAPPER = 17; - public static final int JDK_PREFERENCE = 18; - public static final int ENV_VARIABLES = 19; - public static final int PRIORITY_CLASS = 20; - public static final int DOWNLOAD_URL = 21; - public static final int SUPPORT_URL = 22; - public static final int MUTEX_NAME = 23; - public static final int INSTANCE_WINDOW_TITLE = 24; - public static final int INITIAL_HEAP_SIZE = 25; - public static final int INITIAL_HEAP_PERCENT = 26; - public static final int MAX_HEAP_SIZE = 27; - public static final int MAX_HEAP_PERCENT = 28; - - public static final int STARTUP_ERR = 101; - public static final int BUNDLED_JRE_ERR = 102; - public static final int JRE_VERSION_ERR = 103; - public static final int LAUNCHER_ERR = 104; - public static final int INSTANCE_ALREADY_EXISTS_MSG = 105; - - private final StringBuffer _sb = new StringBuffer(); - - public String getContent() { - return _sb.toString(); - } - - public String getLine(int line) { - return _sb.toString().split("\n")[line - 1]; - } - - public File build(Config c) throws IOException { - _sb.append("LANGUAGE "); - _sb.append(LANG_NEUTRAL); - _sb.append(", "); - _sb.append(SUBLANG_DEFAULT); - _sb.append('\n'); - addVersionInfo(c.getVersionInfo()); - addJre(c.getJre()); - addManifest(MANIFEST, c.getManifest()); - addIcon(APP_ICON, c.getIcon()); - addText(ERR_TITLE, c.getErrTitle()); - addText(DOWNLOAD_URL, c.getDownloadUrl()); - addText(SUPPORT_URL, c.getSupportUrl()); - addText(CMD_LINE, c.getCmdLine()); - addWindowsPath(CHDIR, c.getChdir()); - addText(PRIORITY_CLASS, String.valueOf(c.getPriorityClass())); - addTrue(SET_PROC_NAME, c.isCustomProcName()); - addTrue(GUI_HEADER_STAYS_ALIVE, c.isStayAlive()); - addSplash(c.getSplash()); - addMessages(c); - - if (c.getSingleInstance() != null) { - addText(MUTEX_NAME, c.getSingleInstance().getMutexName()); - addText(INSTANCE_WINDOW_TITLE, c.getSingleInstance().getWindowTitle()); - } - - if (c.getVariables() != null && !c.getVariables().isEmpty()) { - StringBuffer vars = new StringBuffer(); - append(vars, c.getVariables(), "\t"); - addText(ENV_VARIABLES, vars.toString()); - } - - // MAIN_CLASS / JAR - addTrue(WRAPPER, !c.isDontWrapJar()); - if (c.getClassPath() != null) { - addText(MAIN_CLASS, c.getClassPath().getMainClass()); - addWindowsPath(CLASSPATH, c.getClassPath().getPathsString()); - } - if (c.isDontWrapJar() && c.getJar() != null) { - addWindowsPath(JAR, c.getJar().getPath()); - } - - File f = Util.createTempFile("rc"); - BufferedWriter w = new BufferedWriter(new FileWriter(f)); - w.write(_sb.toString()); - w.close(); - return f; - } - - private void addVersionInfo(VersionInfo v) { - if (v == null) { - return; - } - _sb.append("1 VERSIONINFO\n"); - _sb.append("FILEVERSION "); - _sb.append(v.getFileVersion().replaceAll("\\.", ", ")); - _sb.append("\nPRODUCTVERSION "); - _sb.append(v.getProductVersion().replaceAll("\\.", ", ")); - _sb.append("\nFILEFLAGSMASK 0\n" + - "FILEOS 0x40000\n" + - "FILETYPE 1\n" + - "{\n" + - " BLOCK \"StringFileInfo\"\n" + - " {\n" + - " BLOCK \"040904E4\"\n" + // English - " {\n"); - addVerBlockValue("CompanyName", v.getCompanyName()); - addVerBlockValue("FileDescription", v.getFileDescription()); - addVerBlockValue("FileVersion", v.getTxtFileVersion()); - addVerBlockValue("InternalName", v.getInternalName()); - addVerBlockValue("LegalCopyright", v.getCopyright()); - addVerBlockValue("OriginalFilename", v.getOriginalFilename()); - addVerBlockValue("ProductName", v.getProductName()); - addVerBlockValue("ProductVersion", v.getTxtProductVersion()); - _sb.append(" }\n }\nBLOCK \"VarFileInfo\"\n{\nVALUE \"Translation\", 0x0409, 0x04E4\n}\n}"); - } - - private void addJre(Jre jre) { - addWindowsPath(JRE_PATH, jre.getPath()); - addText(JAVA_MIN_VER, jre.getMinVersion()); - addText(JAVA_MAX_VER, jre.getMaxVersion()); - addText(JDK_PREFERENCE, String.valueOf(jre.getJdkPreferenceIndex())); - addInteger(INITIAL_HEAP_SIZE, jre.getInitialHeapSize()); - addInteger(INITIAL_HEAP_PERCENT, jre.getInitialHeapPercent()); - addInteger(MAX_HEAP_SIZE, jre.getMaxHeapSize()); - addInteger(MAX_HEAP_PERCENT, jre.getMaxHeapPercent()); - - StringBuffer options = new StringBuffer(); - if (jre.getOptions() != null && !jre.getOptions().isEmpty()) { - addSpace(options); - append(options, jre.getOptions(), " "); - } - addText(JVM_OPTIONS, options.toString()); - } - - private void addSplash(Splash splash) { - if (splash == null) { - return; - } - addTrue(SHOW_SPLASH, true); - addTrue(SPLASH_WAITS_FOR_WINDOW, splash.getWaitForWindow()); - addText(SPLASH_TIMEOUT, String.valueOf(splash.getTimeout())); - addTrue(SPLASH_TIMEOUT_ERR, splash.isTimeoutErr()); - addBitmap(SPLASH_BITMAP, splash.getFile()); - } - - private void addMessages(Config c) { - Msg msg = c.getMessages(); - if (msg == null) { - msg = new Msg(); - } - addText(STARTUP_ERR, msg.getStartupErr()); - addText(BUNDLED_JRE_ERR, msg.getBundledJreErr()); - addText(JRE_VERSION_ERR, msg.getJreVersionErr()); - addText(LAUNCHER_ERR, msg.getLauncherErr()); - if (c.getSingleInstance() != null) { - addText(INSTANCE_ALREADY_EXISTS_MSG, msg.getInstanceAlreadyExistsMsg()); - } - } - - private void append(StringBuffer sb, List list, String separator) { - for (int i = 0; i < list.size(); i++) { - sb.append(list.get(i)); - if (i < list.size() - 1) { - sb.append(separator); - } - } - } - - private void addText(int id, String text) { - if (text == null || text.equals("")) { - return; - } - _sb.append(id); - _sb.append(" RCDATA BEGIN \""); - _sb.append(escape(text)); - _sb.append("\\0\" END\n"); - } - - private void addTrue(int id, boolean value) { - if (value) { - addText(id, "true"); - } - } - - private void addInteger(int id, Integer value) { - if (value != null) { - addText(id, value.toString()); - } - } - - /** - * Stores path in Windows format with '\' separators. - */ - private void addWindowsPath(int id, String path) { - if (path == null || path.equals("")) { - return; - } - _sb.append(id); - _sb.append(" RCDATA BEGIN \""); - _sb.append(path.replaceAll("\\\\", "\\\\\\\\") - .replaceAll("/", "\\\\\\\\")); - _sb.append("\\0\" END\n"); - } - - private void addManifest(int id, File manifest) { - if (manifest == null || manifest.getPath().equals("")) { - return; - } - _sb.append(id); - _sb.append(" 24 \""); - _sb.append(getPath(Util.getAbsoluteFile( - ConfigPersister.getInstance().getConfigPath(), manifest))); - _sb.append("\"\n"); - } - - private void addIcon(int id, File icon) { - if (icon == null || icon.getPath().equals("")) { - return; - } - _sb.append(id); - _sb.append(" ICON DISCARDABLE \""); - _sb.append(getPath(Util.getAbsoluteFile( - ConfigPersister.getInstance().getConfigPath(), icon))); - _sb.append("\"\n"); - } - - private void addBitmap(int id, File bitmap) { - if (bitmap == null) { - return; - } - _sb.append(id); - _sb.append(" BITMAP \""); - _sb.append(getPath(Util.getAbsoluteFile( - ConfigPersister.getInstance().getConfigPath(), bitmap))); - _sb.append("\"\n"); - } - - private String getPath(File f) { - return f.getPath().replaceAll("\\\\", "\\\\\\\\"); - } - - private void addSpace(StringBuffer sb) { - int len = sb.length(); - if (len-- > 0 && sb.charAt(len) != ' ') { - sb.append(' '); - } - } - - private void addVerBlockValue(String key, String value) { - _sb.append(" VALUE \""); - _sb.append(key); - _sb.append("\", \""); - if (value != null) { - _sb.append(escape(value)); - } - _sb.append("\"\n"); - } - - private String escape(String text) { - return text.replaceAll("\"", "\"\""); - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/Util.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/Util.java deleted file mode 100755 index f3bf2456d6d..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/Util.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on 2005-04-24 - */ -package net.sf.launch4j; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.Reader; -import java.io.Writer; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * @author Copyright (C) 2005 Grzegorz Kowal - */ -public class Util { - public static final boolean WINDOWS_OS = System.getProperty("os.name") - .toLowerCase().startsWith("windows"); - - private Util() {} - - public static File createTempFile(String suffix) throws IOException { - String tmpdir = System.getProperty("launch4j.tmpdir"); - if (tmpdir != null) { - if (tmpdir.indexOf(' ') != -1) { - throw new IOException(Messages.getString("Util.tmpdir")); - } - return File.createTempFile("launch4j", suffix, new File(tmpdir)); - } else { - return File.createTempFile("launch4j", suffix); - } - } - - /** - * Returns the base directory of a jar file or null if the class is a standalone file. - * @return System specific path - * - * Based on a patch submitted by Josh Elsasser - */ - public static File getJarBasedir() { - String url = Util.class.getClassLoader() - .getResource(Util.class.getName().replace('.', '/') + ".class") - .getFile() - .replaceAll("%20", " "); - if (url.startsWith("file:")) { - String jar = url.substring(5, url.lastIndexOf('!')); - int x = jar.lastIndexOf('/'); - if (x == -1) { - x = jar.lastIndexOf('\\'); - } - String basedir = jar.substring(0, x + 1); - return new File(basedir); - } else { - return new File("."); - } - } - - public static File getAbsoluteFile(File basepath, File f) { - return f.isAbsolute() ? f : new File(basepath, f.getPath()); - } - - public static String getExtension(File f) { - String name = f.getName(); - int x = name.lastIndexOf('.'); - if (x != -1) { - return name.substring(x); - } else { - return ""; - } - } - - public static void exec(String[] cmd, Log log) throws ExecException { - BufferedReader is = null; - try { - if (WINDOWS_OS) { - for (int i = 0; i < cmd.length; i++) { - cmd[i] = cmd[i].replaceAll("/", "\\\\"); - } - } - Process p = Runtime.getRuntime().exec(cmd); - is = new BufferedReader(new InputStreamReader(p.getErrorStream())); - String line; - int errLine = -1; - Pattern pattern = Pattern.compile(":\\d+:"); - while ((line = is.readLine()) != null) { - log.append(line); - Matcher matcher = pattern.matcher(line); - if (matcher.find()) { - errLine = Integer.valueOf( - line.substring(matcher.start() + 1, matcher.end() - 1)) - .intValue(); - if (line.matches("(?i).*unrecognized escape sequence")) { - log.append(Messages.getString("Util.use.double.backslash")); - } - break; - } - } - is.close(); - p.waitFor(); - if (errLine != -1) { - throw new ExecException(Messages.getString("Util.exec.failed") - + ": " + cmd, errLine); - } - if (p.exitValue() != 0) { - throw new ExecException(Messages.getString("Util.exec.failed") - + "(" + p.exitValue() + "): " + cmd); - } - } catch (IOException e) { - close(is); - throw new ExecException(e); - } catch (InterruptedException e) { - close(is); - throw new ExecException(e); - } - } - - public static void close(final InputStream o) { - if (o != null) { - try { - o.close(); - } catch (IOException e) { - System.err.println(e); // XXX log - } - } - } - - public static void close(final OutputStream o) { - if (o != null) { - try { - o.close(); - } catch (IOException e) { - System.err.println(e); // XXX log - } - } - } - - public static void close(final Reader o) { - if (o != null) { - try { - o.close(); - } catch (IOException e) { - System.err.println(e); // XXX log - } - } - } - - public static void close(final Writer o) { - if (o != null) { - try { - o.close(); - } catch (IOException e) { - System.err.println(e); // XXX log - } - } - } - - public static boolean delete(File f) { - return (f != null) ? f.delete() : false; - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/ant/AntClassPath.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/ant/AntClassPath.java deleted file mode 100755 index a67bab91f61..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/ant/AntClassPath.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on Jul 19, 2006 - */ -package net.sf.launch4j.ant; - -import java.util.ArrayList; -import java.util.List; - -import net.sf.launch4j.config.ClassPath; - -/** - * @author Copyright (C) 2006 Grzegorz Kowal - */ -public class AntClassPath extends ClassPath { - private final List wrappedPaths = new ArrayList(); - - public void setCp(String cp){ - wrappedPaths.add(cp); - } - - public void addCp(StringWrapper cp) { - wrappedPaths.add(cp); - } - - public void unwrap() { - setPaths(StringWrapper.unwrap(wrappedPaths)); - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/ant/AntConfig.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/ant/AntConfig.java deleted file mode 100755 index 4482436a90c..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/ant/AntConfig.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on May 24, 2005 - */ -package net.sf.launch4j.ant; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import org.apache.tools.ant.BuildException; - -import net.sf.launch4j.config.Config; -import net.sf.launch4j.config.Msg; -import net.sf.launch4j.config.SingleInstance; -import net.sf.launch4j.config.Splash; -import net.sf.launch4j.config.VersionInfo; - -/** - * @author Copyright (C) 2005 Grzegorz Kowal - */ -public class AntConfig extends Config { - private final List wrappedHeaderObjects = new ArrayList(); - private final List wrappedLibs = new ArrayList(); - private final List wrappedVariables = new ArrayList(); - - public void setJarPath(String path) { - setJar(new File(path)); - } - - public void addObj(StringWrapper obj) { - wrappedHeaderObjects.add(obj); - } - - public void addLib(StringWrapper lib) { - wrappedLibs.add(lib); - } - - public void addVar(StringWrapper var) { - wrappedVariables.add(var); - } - - // __________________________________________________________________________________ - - public void addSingleInstance(SingleInstance singleInstance) { - checkNull(getSingleInstance(), "singleInstance"); - setSingleInstance(singleInstance); - } - - public void addClassPath(AntClassPath classPath) { - checkNull(getClassPath(), "classPath"); - setClassPath(classPath); - } - - public void addJre(AntJre jre) { - checkNull(getJre(), "jre"); - setJre(jre); - } - - public void addSplash(Splash splash) { - checkNull(getSplash(), "splash"); - setSplash(splash); - } - - public void addVersionInfo(VersionInfo versionInfo) { - checkNull(getVersionInfo(), "versionInfo"); - setVersionInfo(versionInfo); - } - - public void addMessages(Msg messages) { - checkNull(getMessages(), "messages"); - setMessages(messages); - } - - // __________________________________________________________________________________ - - public void unwrap() { - setHeaderObjects(StringWrapper.unwrap(wrappedHeaderObjects)); - setLibs(StringWrapper.unwrap(wrappedLibs)); - setVariables(StringWrapper.unwrap(wrappedVariables)); - if (getClassPath() != null) { - ((AntClassPath) getClassPath()).unwrap(); - } - if (getJre() != null) { - ((AntJre) getJre()).unwrap(); - } - } - - private void checkNull(Object o, String name) { - if (o != null) { - throw new BuildException( - Messages.getString("AntConfig.duplicate.element") - + ": " - + name); - } - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/ant/AntJre.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/ant/AntJre.java deleted file mode 100755 index b83e3ee02be..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/ant/AntJre.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on Jul 18, 2006 - */ -package net.sf.launch4j.ant; - -import java.util.ArrayList; -import java.util.List; - -import net.sf.launch4j.config.Jre; - -/** - * @author Copyright (C) 2006 Grzegorz Kowal - */ -public class AntJre extends Jre { - private final List wrappedOptions = new ArrayList(); - - public void addOpt(StringWrapper opt) { - wrappedOptions.add(opt); - } - - public void unwrap() { - setOptions(StringWrapper.unwrap(wrappedOptions)); - } - - /** - * For backwards compatibility. - */ - public void setDontUsePrivateJres(boolean dontUse) { - if (dontUse) { - setJdkPreference(JDK_PREFERENCE_JRE_ONLY); - } - else { - setJdkPreference(JDK_PREFERENCE_PREFER_JRE); - } - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/ant/Launch4jTask.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/ant/Launch4jTask.java deleted file mode 100755 index a28287698f8..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/ant/Launch4jTask.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on May 24, 2005 - */ -package net.sf.launch4j.ant; - -import java.io.File; - -import net.sf.launch4j.Builder; -import net.sf.launch4j.BuilderException; -import net.sf.launch4j.Log; -import net.sf.launch4j.config.Config; -import net.sf.launch4j.config.ConfigPersister; -import net.sf.launch4j.config.ConfigPersisterException; - -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Task; - -/** - * @author Copyright (C) 2005 Grzegorz Kowal - */ -public class Launch4jTask extends Task { - private File _configFile; - private AntConfig _config; - - // System properties - private File tmpdir; // launch4j.tmpdir - private File bindir; // launch4j.bindir - - // Override configFile settings - private File jar; - private File outfile; - private String fileVersion; - private String txtFileVersion; - private String productVersion; - private String txtProductVersion; - - public void execute() throws BuildException { - try { - if (tmpdir != null) { - System.setProperty("launch4j.tmpdir", tmpdir.getPath()); - } - if (bindir != null) { - System.setProperty("launch4j.bindir", bindir.getPath()); - } - if (_configFile != null && _config != null) { - throw new BuildException( - Messages.getString("Launch4jTask.specify.config")); - } else if (_configFile != null) { - ConfigPersister.getInstance().load(_configFile); - Config c = ConfigPersister.getInstance().getConfig(); - if (jar != null) { - c.setJar(jar); - } - if (outfile != null) { - c.setOutfile(outfile); - } - if (fileVersion != null) { - c.getVersionInfo().setFileVersion(fileVersion); - } - if (txtFileVersion != null) { - c.getVersionInfo().setTxtFileVersion(txtFileVersion); - } - if (productVersion != null) { - c.getVersionInfo().setProductVersion(productVersion); - } - if (txtProductVersion != null) { - c.getVersionInfo().setTxtProductVersion(txtProductVersion); - } - } else if (_config != null) { - _config.unwrap(); - ConfigPersister.getInstance().setAntConfig(_config, - getProject().getBaseDir()); - } else { - throw new BuildException( - Messages.getString("Launch4jTask.specify.config")); - } - final Builder b = new Builder(Log.getAntLog()); - b.build(); - } catch (ConfigPersisterException e) { - throw new BuildException(e); - } catch (BuilderException e) { - throw new BuildException(e); - } - } - - public void setConfigFile(File configFile) { - _configFile = configFile; - } - - public void addConfig(AntConfig config) { - _config = config; - } - - public void setBindir(File bindir) { - this.bindir = bindir; - } - - public void setTmpdir(File tmpdir) { - this.tmpdir = tmpdir; - } - - public void setFileVersion(String fileVersion) { - this.fileVersion = fileVersion; - } - - public void setJar(File jar) { - this.jar = jar; - } - - public void setJarPath(String path) { - this.jar = new File(path); - } - - public void setOutfile(File outfile) { - this.outfile = outfile; - } - - public void setProductVersion(String productVersion) { - this.productVersion = productVersion; - } - - public void setTxtFileVersion(String txtFileVersion) { - this.txtFileVersion = txtFileVersion; - } - - public void setTxtProductVersion(String txtProductVersion) { - this.txtProductVersion = txtProductVersion; - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/ant/Messages.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/ant/Messages.java deleted file mode 100755 index 0f823f7af7c..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/ant/Messages.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -package net.sf.launch4j.ant; - -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -public class Messages { - private static final String BUNDLE_NAME = "net.sf.launch4j.ant.messages"; - - private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle - .getBundle(BUNDLE_NAME); - - private Messages() { - } - - public static String getString(String key) { - try { - return RESOURCE_BUNDLE.getString(key); - } catch (MissingResourceException e) { - return '!' + key + '!'; - } - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/ant/StringWrapper.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/ant/StringWrapper.java deleted file mode 100755 index 6d38af1a595..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/ant/StringWrapper.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on Jul 18, 2006 - */ -package net.sf.launch4j.ant; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -/** - * @author Copyright (C) 2006 Grzegorz Kowal - */ -public class StringWrapper { - private String text; - - public static List unwrap(List wrappers) { - if (wrappers.isEmpty()) { - return null; - } - List strings = new ArrayList(wrappers.size()); - for (Iterator iter = wrappers.iterator(); iter.hasNext();) { - strings.add(iter.next().toString()); - } - return strings; - } - - public void addText(String text) { - this.text = text; - } - - public String toString() { - return text; - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/ant/messages.properties b/build/windows/launcher/launch4j/src/net/sf/launch4j/ant/messages.properties deleted file mode 100755 index 9666633c2b5..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/ant/messages.properties +++ /dev/null @@ -1,35 +0,0 @@ -# -# Launch4j (http://launch4j.sourceforge.net/) -# Cross-platform Java application wrapper for creating Windows native executables. -# -# Copyright (c) 2004, 2007 Grzegorz Kowal -# -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without modification, -# are permitted provided that the following conditions are met: -# -# * Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# * Neither the name of the Launch4j nor the names of its contributors -# may be used to endorse or promote products derived from this software without -# specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# - -Launch4jTask.specify.config=Specify configFile or config -AntConfig.duplicate.element=Duplicate element diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/ant/messages_es.properties b/build/windows/launcher/launch4j/src/net/sf/launch4j/ant/messages_es.properties deleted file mode 100755 index 9211e8e034a..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/ant/messages_es.properties +++ /dev/null @@ -1,35 +0,0 @@ -# -# Launch4j (http://launch4j.sourceforge.net/) -# Cross-platform Java application wrapper for creating Windows native executables. -# -# Copyright (c) 2004, 2007 Grzegorz Kowal, Patricio Mart�nez Ros -# -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without modification, -# are permitted provided that the following conditions are met: -# -# * Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# * Neither the name of the Launch4j nor the names of its contributors -# may be used to endorse or promote products derived from this software without -# specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# - -Launch4jTask.specify.config=Specify configFile or config -AntConfig.duplicate.element=Duplicate element diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/Binding.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/Binding.java deleted file mode 100755 index 49c9b45ffc7..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/Binding.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on Apr 30, 2005 - */ -package net.sf.launch4j.binding; - -import java.awt.Color; - -/** - * @author Copyright (C) 2005 Grzegorz Kowal - */ -public interface Binding { - /** Used to mark components with invalid data. */ - public final static Color INVALID_COLOR = Color.PINK; - - /** Java Bean property bound to a component */ - public String getProperty(); - /** Clear component, set it to the default value */ - public void clear(IValidatable bean); - /** Java Bean property -> Component */ - public void put(IValidatable bean); - /** Component -> Java Bean property */ - public void get(IValidatable bean); - /** Mark component as valid */ - public void markValid(); - /** Mark component as invalid */ - public void markInvalid(); - /** Enable or disable the component */ - public void setEnabled(boolean enabled); -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/BindingException.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/BindingException.java deleted file mode 100755 index 15dc10cc002..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/BindingException.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on Apr 30, 2005 - */ -package net.sf.launch4j.binding; - -/** - * Signals a runtime error, a missing property in a Java Bean for example. - * - * @author Copyright (C) 2005 Grzegorz Kowal - */ -public class BindingException extends RuntimeException { - public BindingException(Throwable t) { - super(t); - } - - public BindingException(String msg) { - super(msg); - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/Bindings.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/Bindings.java deleted file mode 100755 index 73f507e4999..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/Bindings.java +++ /dev/null @@ -1,317 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on Apr 30, 2005 - */ -package net.sf.launch4j.binding; - -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JList; -import javax.swing.JRadioButton; -import javax.swing.JTextArea; -import javax.swing.JToggleButton; -import javax.swing.text.JTextComponent; - -import org.apache.commons.beanutils.PropertyUtils; - -/** - * Creates and handles bindings. - * - * @author Copyright (C) 2005 Grzegorz Kowal - */ -public class Bindings implements PropertyChangeListener { - private final Map _bindings = new HashMap(); - private final Map _optComponents = new HashMap(); - private boolean _modified = false; - - /** - * Used to track component modifications. - */ - public void propertyChange(PropertyChangeEvent evt) { - String prop = evt.getPropertyName(); - if ("AccessibleValue".equals(prop) - || "AccessibleText".equals(prop) - || "AccessibleVisibleData".equals(prop)) { - _modified = true; - } - } - - /** - * Any of the components modified? - */ - public boolean isModified() { - return _modified; - } - - public Binding getBinding(String property) { - return (Binding) _bindings.get(property); - } - - private void registerPropertyChangeListener(JComponent c) { - c.getAccessibleContext().addPropertyChangeListener(this); - } - - private void registerPropertyChangeListener(JComponent[] cs) { - for (int i = 0; i < cs.length; i++) { - cs[i].getAccessibleContext().addPropertyChangeListener(this); - } - } - - private boolean isPropertyNull(IValidatable bean, Binding b) { - try { - for (Iterator iter = _optComponents.keySet().iterator(); iter.hasNext();) { - String property = (String) iter.next(); - if (b.getProperty().startsWith(property)) { - return PropertyUtils.getProperty(bean, property) == null; - } - } - return false; - } catch (Exception e) { - throw new BindingException(e); - } - } - - /** - * Enables or disables all components bound to properties that begin with given prefix. - */ - public void setComponentsEnabled(String prefix, boolean enabled) { - for (Iterator iter = _bindings.values().iterator(); iter.hasNext();) { - Binding b = (Binding) iter.next(); - if (b.getProperty().startsWith(prefix)) { - b.setEnabled(enabled); - } - } - } - - /** - * Clear all components, set them to their default values. - * Clears the _modified flag. - */ - public void clear(IValidatable bean) { - for (Iterator iter = _optComponents.values().iterator(); iter.hasNext();) { - ((Binding) iter.next()).clear(bean); - } - for (Iterator iter = _bindings.values().iterator(); iter.hasNext();) { - ((Binding) iter.next()).clear(bean); - } - _modified = false; - } - - /** - * Copies data from the Java Bean to the UI components. - * Clears the _modified flag. - */ - public void put(IValidatable bean) { - for (Iterator iter = _optComponents.values().iterator(); iter.hasNext();) { - ((Binding) iter.next()).put(bean); - } - for (Iterator iter = _bindings.values().iterator(); iter.hasNext();) { - Binding b = (Binding) iter.next(); - if (isPropertyNull(bean, b)) { - b.clear(null); - } else { - b.put(bean); - } - } - _modified = false; - } - - /** - * Copies data from UI components to the Java Bean and checks it's class invariants. - * Clears the _modified flag. - * @throws InvariantViolationException - * @throws BindingException - */ - public void get(IValidatable bean) { - try { - for (Iterator iter = _optComponents.values().iterator(); iter.hasNext();) { - ((Binding) iter.next()).get(bean); - } - for (Iterator iter = _bindings.values().iterator(); iter.hasNext();) { - Binding b = (Binding) iter.next(); - if (!isPropertyNull(bean, b)) { - b.get(bean); - } - } - bean.checkInvariants(); - for (Iterator iter = _optComponents.keySet().iterator(); iter.hasNext();) { - String property = (String) iter.next(); - IValidatable component = (IValidatable) PropertyUtils.getProperty(bean, - property); - if (component != null) { - component.checkInvariants(); - } - } - _modified = false; // XXX - } catch (InvariantViolationException e) { - e.setBinding(getBinding(e.getProperty())); - throw e; - } catch (Exception e) { - throw new BindingException(e); - } - } - - private Bindings add(Binding b) { - if (_bindings.containsKey(b.getProperty())) { - throw new BindingException(Messages.getString("Bindings.duplicate.binding")); - } - _bindings.put(b.getProperty(), b); - return this; - } - - /** - * Add an optional (nullable) Java Bean component of type clazz. - */ - public Bindings addOptComponent(String property, Class clazz, JToggleButton c, - boolean enabledByDefault) { - Binding b = new OptComponentBinding(this, property, clazz, c, enabledByDefault); - if (_optComponents.containsKey(property)) { - throw new BindingException(Messages.getString("Bindings.duplicate.binding")); - } - _optComponents.put(property, b); - return this; - } - - /** - * Add an optional (nullable) Java Bean component of type clazz. - */ - public Bindings addOptComponent(String property, Class clazz, JToggleButton c) { - return addOptComponent(property, clazz, c, false); - } - - /** - * Handles JEditorPane, JTextArea, JTextField - */ - public Bindings add(String property, JTextComponent c, String defaultValue) { - registerPropertyChangeListener(c); - return add(new JTextComponentBinding(property, c, defaultValue)); - } - - /** - * Handles JEditorPane, JTextArea, JTextField - */ - public Bindings add(String property, JTextComponent c) { - registerPropertyChangeListener(c); - return add(new JTextComponentBinding(property, c, "")); - } - - /** - * Handles JToggleButton, JCheckBox - */ - public Bindings add(String property, JToggleButton c, boolean defaultValue) { - registerPropertyChangeListener(c); - return add(new JToggleButtonBinding(property, c, defaultValue)); - } - - /** - * Handles JToggleButton, JCheckBox - */ - public Bindings add(String property, JToggleButton c) { - registerPropertyChangeListener(c); - return add(new JToggleButtonBinding(property, c, false)); - } - - /** - * Handles JRadioButton - */ - public Bindings add(String property, JRadioButton[] cs, int defaultValue) { - registerPropertyChangeListener(cs); - return add(new JRadioButtonBinding(property, cs, defaultValue)); - } - - /** - * Handles JRadioButton - */ - public Bindings add(String property, JRadioButton[] cs) { - registerPropertyChangeListener(cs); - return add(new JRadioButtonBinding(property, cs, 0)); - } - - /** - * Handles JTextArea - */ - public Bindings add(String property, JTextArea textArea, String defaultValue) { - registerPropertyChangeListener(textArea); - return add(new JTextComponentBinding(property, textArea, defaultValue)); - } - - /** - * Handles JTextArea lists - */ - public Bindings add(String property, JTextArea textArea) { - registerPropertyChangeListener(textArea); - return add(new JTextAreaBinding(property, textArea)); - } - - /** - * Handles Optional JTextArea lists - */ - public Bindings add(String property, String stateProperty, - JToggleButton button, JTextArea textArea) { - registerPropertyChangeListener(button); - registerPropertyChangeListener(textArea); - return add(new OptJTextAreaBinding(property, stateProperty, button, textArea)); - } - - /** - * Handles JList - */ - public Bindings add(String property, JList list) { - registerPropertyChangeListener(list); - return add(new JListBinding(property, list)); - } - - /** - * Handles JComboBox - */ - public Bindings add(String property, JComboBox combo, int defaultValue) { - registerPropertyChangeListener(combo); - return add(new JComboBoxBinding(property, combo, defaultValue)); - } - - /** - * Handles JComboBox - */ - public Bindings add(String property, JComboBox combo) { - registerPropertyChangeListener(combo); - return add(new JComboBoxBinding(property, combo, 0)); - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/IValidatable.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/IValidatable.java deleted file mode 100755 index fe0dd4862c1..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/IValidatable.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on 2004-01-30 - */ -package net.sf.launch4j.binding; - -/** - * @author Copyright (C) 2004 Grzegorz Kowal - */ -public interface IValidatable { - public void checkInvariants(); -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/InvariantViolationException.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/InvariantViolationException.java deleted file mode 100755 index 2f7f88b1d88..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/InvariantViolationException.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on Jun 23, 2003 - */ -package net.sf.launch4j.binding; - -/** - * @author Copyright (C) 2003 Grzegorz Kowal - */ -public class InvariantViolationException extends RuntimeException { - private final String _property; - private Binding _binding; - - public InvariantViolationException(String msg) { - super(msg); - _property = null; - } - - public InvariantViolationException(String property, String msg) { - super(msg); - _property = property; - } - - public String getProperty() { - return _property; - } - - public Binding getBinding() { - return _binding; - } - - public void setBinding(Binding binding) { - _binding = binding; - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/JComboBoxBinding.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/JComboBoxBinding.java deleted file mode 100755 index 81d6ff28e98..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/JComboBoxBinding.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2007 Ian Roberts - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on May 10, 2005 - */ -package net.sf.launch4j.binding; - -import java.awt.Color; - -import javax.swing.JComboBox; - -import org.apache.commons.beanutils.PropertyUtils; - -/** - * @author Copyright (C) 2007 Ian Roberts - */ -public class JComboBoxBinding implements Binding { - private final String _property; - private final JComboBox _combo; - private final int _defaultValue; - private final Color _validColor; - - public JComboBoxBinding(String property, JComboBox combo, int defaultValue) { - if (property == null || combo == null) { - throw new NullPointerException(); - } - if (property.equals("") - || combo.getItemCount() == 0 - || defaultValue < 0 || defaultValue >= combo.getItemCount()) { - throw new IllegalArgumentException(); - } - _property = property; - _combo = combo; - _defaultValue = defaultValue; - _validColor = combo.getBackground(); - } - - public String getProperty() { - return _property; - } - - public void clear(IValidatable bean) { - select(_defaultValue); - } - - public void put(IValidatable bean) { - try { - Integer i = (Integer) PropertyUtils.getProperty(bean, _property); - if (i == null) { - throw new BindingException( - Messages.getString("JComboBoxBinding.property.null")); - } - select(i.intValue()); - } catch (Exception e) { - throw new BindingException(e); - } - } - - public void get(IValidatable bean) { - try { - PropertyUtils.setProperty(bean, _property, new Integer(_combo.getSelectedIndex())); - return; - } catch (Exception e) { - throw new BindingException(e); - } - } - - private void select(int index) { - if (index < 0 || index >= _combo.getItemCount()) { - throw new BindingException( - Messages.getString("JComboBoxBinding.index.out.of.bounds")); - } - _combo.setSelectedIndex(index); - } - - public void markValid() { - _combo.setBackground(_validColor); - _combo.requestFocusInWindow(); - } - - public void markInvalid() { - _combo.setBackground(Binding.INVALID_COLOR); - } - - public void setEnabled(boolean enabled) { - _combo.setEnabled(enabled); - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/JListBinding.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/JListBinding.java deleted file mode 100755 index 31dec58c180..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/JListBinding.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on May 1, 2006 - */ -package net.sf.launch4j.binding; - -import java.awt.Color; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import javax.swing.DefaultListModel; -import javax.swing.JList; - -import org.apache.commons.beanutils.PropertyUtils; - -/** - * @author Copyright (C) 2006 Grzegorz Kowal - */ -public class JListBinding implements Binding { - private final String _property; - private final JList _list; - private final Color _validColor; - - public JListBinding(String property, JList list) { - if (property == null || list == null) { - throw new NullPointerException(); - } - if (property.equals("")) { - throw new IllegalArgumentException(); - } - _property = property; - _list = list; - _validColor = _list.getBackground(); - } - - public String getProperty() { - return _property; - } - - public void clear(IValidatable bean) { - _list.setModel(new DefaultListModel()); - } - - public void put(IValidatable bean) { - try { - DefaultListModel model = new DefaultListModel(); - List list = (List) PropertyUtils.getProperty(bean, _property); - if (list != null) { - for (Iterator iter = list.iterator(); iter.hasNext();) { - model.addElement(iter.next()); - } - } - _list.setModel(model); - } catch (Exception e) { - throw new BindingException(e); - } - } - - public void get(IValidatable bean) { - try { - DefaultListModel model = (DefaultListModel) _list.getModel(); - final int size = model.getSize(); - List list = new ArrayList(size); - for (int i = 0; i < size; i++) { - list.add(model.get(i)); - } - PropertyUtils.setProperty(bean, _property, list); - } catch (Exception e) { - throw new BindingException(e); - } - } - - public void markValid() { - _list.setBackground(_validColor); - _list.requestFocusInWindow(); - } - - public void markInvalid() { - _list.setBackground(Binding.INVALID_COLOR); - } - - public void setEnabled(boolean enabled) { - _list.setEnabled(enabled); - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/JRadioButtonBinding.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/JRadioButtonBinding.java deleted file mode 100755 index 9d922bedf7e..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/JRadioButtonBinding.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on May 10, 2005 - */ -package net.sf.launch4j.binding; - -import java.awt.Color; - -import javax.swing.JRadioButton; - -import org.apache.commons.beanutils.PropertyUtils; - -/** - * @author Copyright (C) 2005 Grzegorz Kowal - */ -public class JRadioButtonBinding implements Binding { - private final String _property; - private final JRadioButton[] _buttons; - private final int _defaultValue; - private final Color _validColor; - - public JRadioButtonBinding(String property, JRadioButton[] buttons, int defaultValue) { - if (property == null || buttons == null) { - throw new NullPointerException(); - } - for (int i = 0; i < buttons.length; i++) { - if (buttons[i] == null) { - throw new NullPointerException(); - } - } - if (property.equals("") - || buttons.length == 0 - || defaultValue < 0 || defaultValue >= buttons.length) { - throw new IllegalArgumentException(); - } - _property = property; - _buttons = buttons; - _defaultValue = defaultValue; - _validColor = buttons[0].getBackground(); - } - - public String getProperty() { - return _property; - } - - public void clear(IValidatable bean) { - select(_defaultValue); - } - - public void put(IValidatable bean) { - try { - Integer i = (Integer) PropertyUtils.getProperty(bean, _property); - if (i == null) { - throw new BindingException( - Messages.getString("JRadioButtonBinding.property.null")); - } - select(i.intValue()); - } catch (Exception e) { - throw new BindingException(e); - } - } - - public void get(IValidatable bean) { - try { - for (int i = 0; i < _buttons.length; i++) { - if (_buttons[i].isSelected()) { - PropertyUtils.setProperty(bean, _property, new Integer(i)); - return; - } - } - throw new BindingException( - Messages.getString("JRadioButtonBinding.nothing.selected")); - } catch (Exception e) { - throw new BindingException(e); - } - } - - private void select(int index) { - if (index < 0 || index >= _buttons.length) { - throw new BindingException( - Messages.getString("JRadioButtonBinding.index.out.of.bounds")); - } - _buttons[index].setSelected(true); - } - - public void markValid() { - for (int i = 0; i < _buttons.length; i++) { - if (_buttons[i].isSelected()) { - _buttons[i].setBackground(_validColor); - _buttons[i].requestFocusInWindow(); - return; - } - } - throw new BindingException( - Messages.getString("JRadioButtonBinding.nothing.selected")); - } - - public void markInvalid() { - for (int i = 0; i < _buttons.length; i++) { - if (_buttons[i].isSelected()) { - _buttons[i].setBackground(Binding.INVALID_COLOR); - return; - } - } - throw new BindingException( - Messages.getString("JRadioButtonBinding.nothing.selected")); - } - - public void setEnabled(boolean enabled) { - for (int i = 0; i < _buttons.length; i++) { - _buttons[i].setEnabled(enabled); - } - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/JTextAreaBinding.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/JTextAreaBinding.java deleted file mode 100755 index d4e8a2c6590..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/JTextAreaBinding.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on Jun 14, 2006 - */ -package net.sf.launch4j.binding; - -import java.awt.Color; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JTextArea; - -import org.apache.commons.beanutils.PropertyUtils; - -/** - * @author Copyright (C) 2006 Grzegorz Kowal - */ -public class JTextAreaBinding implements Binding { - private final String _property; - private final JTextArea _textArea; - private final Color _validColor; - - public JTextAreaBinding(String property, JTextArea textArea) { - if (property == null || textArea == null) { - throw new NullPointerException(); - } - if (property.equals("")) { - throw new IllegalArgumentException(); - } - _property = property; - _textArea = textArea; - _validColor = _textArea.getBackground(); - } - - public String getProperty() { - return _property; - } - - public void clear(IValidatable bean) { - put(bean); - } - - public void put(IValidatable bean) { - try { - List list = (List) PropertyUtils.getProperty(bean, _property); - StringBuffer sb = new StringBuffer(); - if (list != null) { - for (int i = 0; i < list.size(); i++) { - sb.append(list.get(i)); - if (i < list.size() - 1) { - sb.append("\n"); - } - } - } - _textArea.setText(sb.toString()); - } catch (Exception e) { - throw new BindingException(e); - } - } - - public void get(IValidatable bean) { - try { - String text = _textArea.getText(); - if (!text.equals("")) { - String[] items = text.split("\n"); - List list = new ArrayList(); - for (int i = 0; i < items.length; i++) { - list.add(items[i]); - } - PropertyUtils.setProperty(bean, _property, list); - } else { - PropertyUtils.setProperty(bean, _property, null); - } - } catch (Exception e) { - throw new BindingException(e); - } - } - - public void markValid() { - _textArea.setBackground(_validColor); - _textArea.requestFocusInWindow(); - } - - public void markInvalid() { - _textArea.setBackground(Binding.INVALID_COLOR); - } - - public void setEnabled(boolean enabled) { - _textArea.setEnabled(enabled); - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/JTextComponentBinding.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/JTextComponentBinding.java deleted file mode 100755 index 6b0dd1b0b28..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/JTextComponentBinding.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on Apr 30, 2005 - */ -package net.sf.launch4j.binding; - -import java.awt.Color; - -import javax.swing.text.JTextComponent; - -import org.apache.commons.beanutils.BeanUtils; - -/** - * Handles JEditorPane, JTextArea, JTextField - * - * @author Copyright (C) 2005 Grzegorz Kowal - */ -public class JTextComponentBinding implements Binding { - private final String _property; - private final JTextComponent _textComponent; - private final String _defaultValue; - private final Color _validColor; - - public JTextComponentBinding(String property, JTextComponent textComponent, - String defaultValue) { - if (property == null || textComponent == null || defaultValue == null) { - throw new NullPointerException(); - } - if (property.equals("")) { - throw new IllegalArgumentException(); - } - _property = property; - _textComponent = textComponent; - _defaultValue = defaultValue; - _validColor = _textComponent.getBackground(); - } - - public String getProperty() { - return _property; - } - - public void clear(IValidatable bean) { - _textComponent.setText(_defaultValue); - } - - public void put(IValidatable bean) { - try { - String s = BeanUtils.getProperty(bean, _property); - // XXX displays zeros as blank - _textComponent.setText(s != null && !s.equals("0") ? s : ""); - } catch (Exception e) { - throw new BindingException(e); - } - } - - public void get(IValidatable bean) { - try { - BeanUtils.setProperty(bean, _property, _textComponent.getText()); - } catch (Exception e) { - throw new BindingException(e); - } - } - - public void markValid() { - _textComponent.setBackground(_validColor); - _textComponent.requestFocusInWindow(); - } - - public void markInvalid() { - _textComponent.setBackground(Binding.INVALID_COLOR); - } - - public void setEnabled(boolean enabled) { - _textComponent.setEnabled(enabled); - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/JToggleButtonBinding.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/JToggleButtonBinding.java deleted file mode 100755 index a7055cccc5e..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/JToggleButtonBinding.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on Apr 30, 2005 - */ -package net.sf.launch4j.binding; - -import java.awt.Color; - -import javax.swing.JToggleButton; - -import org.apache.commons.beanutils.PropertyUtils; - -/** - * Handles JToggleButton, JCheckBox - * - * @author Copyright (C) 2005 Grzegorz Kowal - */ -public class JToggleButtonBinding implements Binding { - private final String _property; - private final JToggleButton _button; - private final boolean _defaultValue; - private final Color _validColor; - - public JToggleButtonBinding(String property, JToggleButton button, - boolean defaultValue) { - if (property == null || button == null) { - throw new NullPointerException(); - } - if (property.equals("")) { - throw new IllegalArgumentException(); - } - _property = property; - _button = button; - _defaultValue = defaultValue; - _validColor = _button.getBackground(); - } - - public String getProperty() { - return _property; - } - - public void clear(IValidatable bean) { - _button.setSelected(_defaultValue); - } - - public void put(IValidatable bean) { - try { - Boolean b = (Boolean) PropertyUtils.getProperty(bean, _property); - _button.setSelected(b != null && b.booleanValue()); - } catch (Exception e) { - throw new BindingException(e); - } - } - - public void get(IValidatable bean) { - try { - PropertyUtils.setProperty(bean, _property, - Boolean.valueOf(_button.isSelected())); - } catch (Exception e) { - throw new BindingException(e); - } - } - - public void markValid() { - _button.setBackground(_validColor); - _button.requestFocusInWindow(); - } - - public void markInvalid() { - _button.setBackground(Binding.INVALID_COLOR); - } - - public void setEnabled(boolean enabled) { - _button.setEnabled(enabled); - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/Messages.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/Messages.java deleted file mode 100755 index 91ddff2b13c..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/Messages.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -package net.sf.launch4j.binding; - -import java.text.MessageFormat; -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -public class Messages { - private static final String BUNDLE_NAME = "net.sf.launch4j.binding.messages"; - - private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle - .getBundle(BUNDLE_NAME); - private static final MessageFormat FORMATTER = new MessageFormat(""); - - private Messages() { - } - - public static String getString(String key) { - try { - return RESOURCE_BUNDLE.getString(key); - } catch (MissingResourceException e) { - return '!' + key + '!'; - } - } - - public static String getString(String key, String arg0) { - return getString(key, new Object[] {arg0}); - } - - public static String getString(String key, String arg0, String arg1) { - return getString(key, new Object[] {arg0, arg1}); - } - - public static String getString(String key, String arg0, String arg1, String arg2) { - return getString(key, new Object[] {arg0, arg1, arg2}); - } - - public static String getString(String key, Object[] args) { - try { - FORMATTER.applyPattern(RESOURCE_BUNDLE.getString(key)); - return FORMATTER.format(args); - } catch (MissingResourceException e) { - return '!' + key + '!'; - } - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/OptComponentBinding.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/OptComponentBinding.java deleted file mode 100755 index b573da6282a..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/OptComponentBinding.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on May 11, 2005 - */ -package net.sf.launch4j.binding; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.Arrays; - -import javax.swing.JToggleButton; - -import org.apache.commons.beanutils.PropertyUtils; - -/** - * @author Copyright (C) 2005 Grzegorz Kowal - */ -public class OptComponentBinding implements Binding, ActionListener { - private final Bindings _bindings; - private final String _property; - private final Class _clazz; - private final JToggleButton _button; - private final boolean _enabledByDefault; - - public OptComponentBinding(Bindings bindings, String property, Class clazz, - JToggleButton button, boolean enabledByDefault) { - if (property == null || clazz == null || button == null) { - throw new NullPointerException(); - } - if (property.equals("")) { - throw new IllegalArgumentException(); - } - if (!Arrays.asList(clazz.getInterfaces()).contains(IValidatable.class)) { - throw new IllegalArgumentException( - Messages.getString("OptComponentBinding.must.implement") - + IValidatable.class); - } - _bindings = bindings; - _property = property; - _clazz = clazz; - _button = button; - _button.addActionListener(this); - _enabledByDefault = enabledByDefault; - } - - public String getProperty() { - return _property; - } - - public void clear(IValidatable bean) { - _button.setSelected(_enabledByDefault); - updateComponents(); - } - - public void put(IValidatable bean) { - try { - Object component = PropertyUtils.getProperty(bean, _property); - _button.setSelected(component != null); - updateComponents(); - } catch (Exception e) { - throw new BindingException(e); - } - } - - public void get(IValidatable bean) { - try { - PropertyUtils.setProperty(bean, _property, _button.isSelected() - ? _clazz.newInstance() : null); - } catch (Exception e) { - throw new BindingException(e); - } - } - - public void markValid() {} - - public void markInvalid() {} - - public void setEnabled(boolean enabled) {} // XXX implement? - - public void actionPerformed(ActionEvent e) { - updateComponents(); - } - - private void updateComponents() { - _bindings.setComponentsEnabled(_property, _button.isSelected()); - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/OptJTextAreaBinding.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/OptJTextAreaBinding.java deleted file mode 100755 index 3cea776d7b1..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/OptJTextAreaBinding.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on Sep 3, 2005 - */ -package net.sf.launch4j.binding; - -import java.awt.Color; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JTextArea; -import javax.swing.JToggleButton; - -import org.apache.commons.beanutils.BeanUtils; -import org.apache.commons.beanutils.PropertyUtils; - -/** - * @author Copyright (C) 2005 Grzegorz Kowal - */ -public class OptJTextAreaBinding implements Binding, ActionListener { - private final String _property; - private final String _stateProperty; - private final JToggleButton _button; - private final JTextArea _textArea; - private final Color _validColor; - - public OptJTextAreaBinding(String property, String stateProperty, - JToggleButton button, JTextArea textArea) { - if (property == null || button == null || textArea == null) { - throw new NullPointerException(); - } - if (property.equals("")) { - throw new IllegalArgumentException(); - } - _property = property; - _stateProperty = stateProperty; - _button = button; - _textArea = textArea; - _validColor = _textArea.getBackground(); - button.addActionListener(this); - } - - public String getProperty() { - return _property; - } - - public void clear(IValidatable bean) { - put(bean); - } - - public void put(IValidatable bean) { - try { - boolean selected = "true".equals(BeanUtils.getProperty(bean, - _stateProperty)); - _button.setSelected(selected); - _textArea.setEnabled(selected); - List list = (List) PropertyUtils.getProperty(bean, _property); - StringBuffer sb = new StringBuffer(); - if (list != null) { - for (int i = 0; i < list.size(); i++) { - sb.append(list.get(i)); - if (i < list.size() - 1) { - sb.append("\n"); - } - } - } - _textArea.setText(sb.toString()); - } catch (Exception e) { - throw new BindingException(e); - } - } - - public void get(IValidatable bean) { - try { - String text = _textArea.getText(); - if (_button.isSelected() && !text.equals("")) { - String[] items = text.split("\n"); - List list = new ArrayList(); - for (int i = 0; i < items.length; i++) { - list.add(items[i]); - } - PropertyUtils.setProperty(bean, _property, list); - } else { - PropertyUtils.setProperty(bean, _property, null); - } - } catch (Exception e) { - throw new BindingException(e); - } - } - - public void markValid() { - _textArea.setBackground(_validColor); - _textArea.requestFocusInWindow(); - } - - public void markInvalid() { - _textArea.setBackground(Binding.INVALID_COLOR); - } - - public void setEnabled(boolean enabled) { - _textArea.setEnabled(enabled); - } - - public void actionPerformed(ActionEvent e) { - _textArea.setEnabled(_button.isSelected()); - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/Validator.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/Validator.java deleted file mode 100755 index 88ea67c3396..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/Validator.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on 2004-01-30 - */ -package net.sf.launch4j.binding; - -import java.io.File; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; - -import net.sf.launch4j.Util; -import net.sf.launch4j.config.ConfigPersister; - -/** - * @author Copyright (C) 2004 Grzegorz Kowal - */ -public class Validator { - public static final String ALPHANUMERIC_PATTERN = "[\\w]*?"; - public static final String ALPHA_PATTERN = "[\\w&&\\D]*?"; - public static final String NUMERIC_PATTERN = "[\\d]*?"; - public static final String PATH_PATTERN = "[\\w|[ .,:\\-/\\\\]]*?"; - - public static final int MAX_STR = 128; - public static final int MAX_PATH = 260; - public static final int MAX_BIG_STR = 8192; // or 16384; - public static final int MAX_ARGS = 32767 - 2048; - - private Validator() {} - - public static boolean isEmpty(String s) { - return s == null || s.equals(""); - } - - public static void checkNotNull(Object o, String property, String name) { - if (o == null) { - signalViolation(property, - Messages.getString("Validator.empty.field", name)); - } - } - - public static void checkString(String s, int maxLength, String property, - String name) { - if (s == null || s.length() == 0) { - signalViolation(property, - Messages.getString("Validator.empty.field", name)); - } - if (s.length() > maxLength) { - signalLengthViolation(property, name, maxLength); - } - } - - public static void checkOptStrings(List strings, int maxLength, int totalMaxLength, - String property, String name) { - if (strings == null) { - return; - } - int totalLength = 0; - for (Iterator iter = strings.iterator(); iter.hasNext();) { - String s = (String) iter.next(); - checkString(s, maxLength, property, name); - totalLength += s.length(); - if (totalLength > totalMaxLength) { - signalLengthViolation(property, name, totalMaxLength); - } - } - } - - public static void checkString(String s, int maxLength, String pattern, - String property, String name) { - checkString(s, maxLength, property, name); - if (!s.matches(pattern)) { - signalViolation(property, - Messages.getString("Validator.invalid.data", name)); - } - } - - public static void checkOptStrings(List strings, int maxLength, int totalMaxLength, - String pattern, String property, String name, String msg) { - if (strings == null) { - return; - } - int totalLength = 0; - for (Iterator iter = strings.iterator(); iter.hasNext();) { - String s = (String) iter.next(); - checkString(s, maxLength, property, name); - if (!s.matches(pattern)) { - signalViolation(property, msg != null - ? msg - : Messages.getString("Validator.invalid.data", name)); - } - totalLength += s.length(); - if (totalLength > totalMaxLength) { - signalLengthViolation(property, name, totalMaxLength); - } - } - } - - public static void checkOptString(String s, int maxLength, String property, - String name) { - if (s == null || s.length() == 0) { - return; - } - if (s.length() > maxLength) { - signalLengthViolation(property, name, maxLength); - } - } - - public static void checkOptString(String s, int maxLength, String pattern, - String property, String name) { - if (s == null || s.length() == 0) { - return; - } - if (s.length() > maxLength) { - signalLengthViolation(property, name, maxLength); - } - if (!s.matches(pattern)) { - signalViolation(property, - Messages.getString("Validator.invalid.data", name)); - } - } - - public static void checkRange(int value, int min, int max, - String property, String name) { - if (value < min || value > max) { - signalViolation(property, - Messages.getString("Validator.must.be.in.range", name, - String.valueOf(min), String.valueOf(max))); - } - } - - public static void checkRange(char value, char min, char max, - String property, String name) { - if (value < min || value > max) { - signalViolation(property, Messages.getString("Validator.must.be.in.range", - name, String.valueOf(min), String.valueOf(max))); - } - } - - public static void checkMin(int value, int min, String property, String name) { - if (value < min) { - signalViolation(property, - Messages.getString("Validator.must.be.at.least", name, - String.valueOf(min))); - } - } - - public static void checkIn(String s, String[] strings, String property, - String name) { - if (isEmpty(s)) { - signalViolation(property, - Messages.getString("Validator.empty.field", name)); - } - List list = Arrays.asList(strings); - if (!list.contains(s)) { - signalViolation(property, - Messages.getString("Validator.invalid.option", name, list.toString())); - } - } - - public static void checkTrue(boolean condition, String property, String msg) { - if (!condition) { - signalViolation(property, msg); - } - } - - public static void checkFalse(boolean condition, String property, String msg) { - if (condition) { - signalViolation(property, msg); - } - } - - public static void checkElementsNotNullUnique(Collection c, String property, - String msg) { - if (c.contains(null) - || new HashSet(c).size() != c.size()) { - signalViolation(property, - Messages.getString("Validator.already.exists", msg)); - } - } - - public static void checkElementsUnique(Collection c, String property, String msg) { - if (new HashSet(c).size() != c.size()) { - signalViolation(property, - Messages.getString("Validator.already.exists", msg)); - } - } - - public static void checkFile(File f, String property, String fileDescription) { - File cfgPath = ConfigPersister.getInstance().getConfigPath(); - if (f == null - || f.getPath().equals("") - || (!f.exists() && !Util.getAbsoluteFile(cfgPath, f).exists())) { - signalViolation(property, - Messages.getString("Validator.doesnt.exist", fileDescription)); - } - } - - public static void checkOptFile(File f, String property, String fileDescription) { - if (f != null && f.getPath().length() > 0) { - checkFile(f, property, fileDescription); - } - } - - public static void checkRelativeWinPath(String path, String property, String msg) { - if (path == null - || path.equals("") - || path.startsWith("/") - || path.startsWith("\\") - || path.indexOf(':') != -1) { - signalViolation(property, msg); - } - } - - public static void signalLengthViolation(String property, String name, - int maxLength) { - signalViolation(property, - Messages.getString("Validator.exceeds.max.length", name, - String.valueOf(maxLength))); - } - - public static void signalViolation(String property, String msg) { - throw new InvariantViolationException(property, msg); - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/messages.properties b/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/messages.properties deleted file mode 100755 index adb5a8886b7..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/messages.properties +++ /dev/null @@ -1,52 +0,0 @@ -# -# Launch4j (http://launch4j.sourceforge.net/) -# Cross-platform Java application wrapper for creating Windows native executables. -# -# Copyright (c) 2004, 2007 Grzegorz Kowal -# -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without modification, -# are permitted provided that the following conditions are met: -# -# * Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# * Neither the name of the Launch4j nor the names of its contributors -# may be used to endorse or promote products derived from this software without -# specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# - -OptComponentBinding.must.implement=Optional component must implement - -Validator.empty.field=Enter: {0} -Validator.invalid.data=Invalid data: {0} -Validator.must.be.in.range={0} must be in range [{1}-{2}] -Validator.must.be.at.least={0} must be at least -Validator.already.exists={0} already exists. -Validator.doesnt.exist={0} doesn''t exist. -Validator.exceeds.max.length={0} exceeds the maximum length of {1} characters. -Validator.invalid.option={0} must be one of [{1}] - -Bindings.duplicate.binding=Duplicate binding - -JRadioButtonBinding.property.null=Property is null -JRadioButtonBinding.nothing.selected=Nothing selected -JRadioButtonBinding.index.out.of.bounds=Button index out of bounds - -JComboBoxBinding.property.null=Property is null -JComboBoxBinding.index.out.of.bounds=Combo box index out of bounds diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/messages_es.properties b/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/messages_es.properties deleted file mode 100755 index e2e50fcb46d..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/binding/messages_es.properties +++ /dev/null @@ -1,51 +0,0 @@ -# -# Launch4j (http://launch4j.sourceforge.net/) -# Cross-platform Java application wrapper for creating Windows native executables. -# -# Copyright (c) 2004, 2007 Grzegorz Kowal, Patricio Mart�nez Ros -# -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without modification, -# are permitted provided that the following conditions are met: -# -# * Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# * Neither the name of the Launch4j nor the names of its contributors -# may be used to endorse or promote products derived from this software without -# specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# - -OptComponentBinding.must.implement=El componente opcional debe ser implementado - -Validator.empty.field=Introduzca: {0} -Validator.invalid.data=Dato no v�lido: {0} -Validator.must.be.in.range={0} debe estar en el rango [{1}-{2}] -Validator.must.be.at.least={0} deb ser al menos -Validator.already.exists={0} ya existe. -Validator.doesnt.exist={0} no existe. -Validator.exceeds.max.length={0} excede la longitud m�xima de {1} caracteres. -Validator.invalid.option={0} must be one of [{1}] - -Bindings.duplicate.binding=Binding duplicado - -JRadioButtonBinding.property.null=La propiedad es nula -JRadioButtonBinding.nothing.selected=Nada seleccionado -JRadioButtonBinding.index.out.of.bounds=�ndice de bot�n fuera de l�mite -JComboBoxBinding.property.null=Property is null -JComboBoxBinding.index.out.of.bounds=Combo box index out of bounds diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/config/ClassPath.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/config/ClassPath.java deleted file mode 100755 index da7dbd6c453..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/config/ClassPath.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on May 1, 2006 - */ -package net.sf.launch4j.config; - -import java.util.List; - -import net.sf.launch4j.binding.IValidatable; -import net.sf.launch4j.binding.Validator; - -/** - * @author Copyright (C) 2006 Grzegorz Kowal - */ -public class ClassPath implements IValidatable { - private String mainClass; - private List paths; - - public void checkInvariants() { - Validator.checkString(mainClass, Validator.MAX_PATH, "mainClass", - Messages.getString("ClassPath.mainClass")); - Validator.checkOptStrings(paths, - Validator.MAX_PATH, - Validator.MAX_BIG_STR, - "paths", - Messages.getString("ClassPath.path")); - } - - public String getMainClass() { - return mainClass; - } - - public void setMainClass(String mainClass) { - this.mainClass = mainClass; - } - - public List getPaths() { - return paths; - } - - public void setPaths(List paths) { - this.paths = paths; - } - - public String getPathsString() { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < paths.size(); i++) { - sb.append(paths.get(i)); - if (i < paths.size() - 1) { - sb.append(';'); - } - } - return sb.toString(); - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/config/Config.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/config/Config.java deleted file mode 100755 index 27633bfb4cf..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/config/Config.java +++ /dev/null @@ -1,396 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on Apr 21, 2005 - */ -package net.sf.launch4j.config; - -import java.io.File; -import java.util.Arrays; -import java.util.List; - -import net.sf.launch4j.binding.IValidatable; -import net.sf.launch4j.binding.Validator; - -/** - * @author Copyright (C) 2005 Grzegorz Kowal - */ -public class Config implements IValidatable { - - // 1.x config properties_____________________________________________________________ - public static final String HEADER = "header"; - public static final String JAR = "jar"; - public static final String OUTFILE = "outfile"; - public static final String ERR_TITLE = "errTitle"; - public static final String JAR_ARGS = "jarArgs"; - public static final String CHDIR = "chdir"; - public static final String CUSTOM_PROC_NAME = "customProcName"; - public static final String STAY_ALIVE = "stayAlive"; - public static final String ICON = "icon"; - - // __________________________________________________________________________________ - public static final String DOWNLOAD_URL = "http://java.com/download"; - - public static final String GUI_HEADER = "gui"; - public static final String CONSOLE_HEADER = "console"; - - private static final String[] HEADER_TYPES = new String[] { GUI_HEADER, - CONSOLE_HEADER }; - - private static final String[] PRIORITY_CLASS_NAMES = new String[] { "normal", - "idle", - "high" }; - - private static final int[] PRIORITY_CLASSES = new int[] { 0x00000020, - 0x00000040, - 0x00000080 }; - - private boolean dontWrapJar; - private String headerType = GUI_HEADER; - private List headerObjects; - private List libs; - private File jar; - private File outfile; - - // Runtime header configuration - private String errTitle; - private String cmdLine; - private String chdir; - private String priority; - private String downloadUrl; - private String supportUrl; - private boolean customProcName; - private boolean stayAlive; - private File manifest; - private File icon; - private List variables; - private SingleInstance singleInstance; - private ClassPath classPath; - private Jre jre; - private Splash splash; - private VersionInfo versionInfo; - private Msg messages; - - public void checkInvariants() { - Validator.checkTrue(outfile != null && outfile.getPath().endsWith(".exe"), - "outfile", Messages.getString("Config.specify.output.exe")); - if (dontWrapJar) { - if (jar != null && !jar.getPath().equals("")) { - Validator.checkRelativeWinPath(jar.getPath(), "jar", - Messages.getString("Config.application.jar.path")); - } else { - Validator.checkTrue(classPath != null, "classPath", - Messages.getString("ClassPath.or.jar")); - } - } else { - Validator.checkFile(jar, "jar", - Messages.getString("Config.application.jar")); - } - if (!Validator.isEmpty(chdir)) { - Validator.checkRelativeWinPath(chdir, "chdir", - Messages.getString("Config.chdir.relative")); - Validator.checkFalse(chdir.toLowerCase().equals("true") - || chdir.toLowerCase().equals("false"), - "chdir", Messages.getString("Config.chdir.path")); - } - Validator.checkOptFile(manifest, "manifest", Messages.getString("Config.manifest")); - Validator.checkOptFile(icon, "icon", Messages.getString("Config.icon")); - Validator.checkOptString(cmdLine, Validator.MAX_BIG_STR, "jarArgs", - Messages.getString("Config.jar.arguments")); - Validator.checkOptString(errTitle, Validator.MAX_STR, "errTitle", - Messages.getString("Config.error.title")); - Validator.checkOptString(downloadUrl, 256, - "downloadUrl", Messages.getString("Config.download.url")); - Validator.checkOptString(supportUrl, 256, - "supportUrl", Messages.getString("Config.support.url")); - Validator.checkIn(getHeaderType(), HEADER_TYPES, "headerType", - Messages.getString("Config.header.type")); - Validator.checkFalse(getHeaderType().equals(CONSOLE_HEADER) && splash != null, - "headerType", - Messages.getString("Config.splash.not.impl.by.console.hdr")); - Validator.checkOptStrings(variables, - Validator.MAX_ARGS, - Validator.MAX_ARGS, - "[^=%\t]+=[^=\t]+", - "variables", - Messages.getString("Config.variables"), - Messages.getString("Config.variables.err")); - Validator.checkIn(getPriority(), PRIORITY_CLASS_NAMES, "priority", - Messages.getString("Config.priority")); - jre.checkInvariants(); - } - - public void validate() { - checkInvariants(); - if (classPath != null) { - classPath.checkInvariants(); - } - if (splash != null) { - splash.checkInvariants(); - } - if (versionInfo != null) { - versionInfo.checkInvariants(); - } - } - - /** Change current directory to EXE location. */ - public String getChdir() { - return chdir; - } - - public void setChdir(String chdir) { - this.chdir = chdir; - } - - /** Constant command line arguments passed to the application. */ - public String getCmdLine() { - return cmdLine; - } - - public void setCmdLine(String cmdLine) { - this.cmdLine = cmdLine; - } - - /** Optional, error message box title. */ - public String getErrTitle() { - return errTitle; - } - - public void setErrTitle(String errTitle) { - this.errTitle = errTitle; - } - - /** launch4j header file. */ - public String getHeaderType() { - return headerType.toLowerCase(); - } - - public void setHeaderType(String headerType) { - this.headerType = headerType; - } - - /** launch4j header file index - used by GUI. */ - public int getHeaderTypeIndex() { - int x = Arrays.asList(HEADER_TYPES).indexOf(getHeaderType()); - return x != -1 ? x : 0; - } - - public void setHeaderTypeIndex(int headerTypeIndex) { - headerType = HEADER_TYPES[headerTypeIndex]; - } - - public boolean isCustomHeaderObjects() { - return headerObjects != null && !headerObjects.isEmpty(); - } - - public List getHeaderObjects() { - return isCustomHeaderObjects() ? headerObjects - : getHeaderType().equals(GUI_HEADER) - ? LdDefaults.GUI_HEADER_OBJECTS - : LdDefaults.CONSOLE_HEADER_OBJECTS; - } - - public void setHeaderObjects(List headerObjects) { - this.headerObjects = headerObjects; - } - - public boolean isCustomLibs() { - return libs != null && !libs.isEmpty(); - } - - public List getLibs() { - return isCustomLibs() ? libs : LdDefaults.LIBS; - } - - public void setLibs(List libs) { - this.libs = libs; - } - - /** Wrapper's manifest for User Account Control. */ - public File getManifest() { - return manifest; - } - - public void setManifest(File manifest) { - this.manifest = manifest; - } - - /** ICO file. */ - public File getIcon() { - return icon; - } - - public void setIcon(File icon) { - this.icon = icon; - } - - /** Jar to wrap. */ - public File getJar() { - return jar; - } - - public void setJar(File jar) { - this.jar = jar; - } - - public List getVariables() { - return variables; - } - - public void setVariables(List variables) { - this.variables = variables; - } - - public ClassPath getClassPath() { - return classPath; - } - - public void setClassPath(ClassPath classpath) { - this.classPath = classpath; - } - - /** JRE configuration */ - public Jre getJre() { - return jre; - } - - public void setJre(Jre jre) { - this.jre = jre; - } - - /** Output EXE file. */ - public File getOutfile() { - return outfile; - } - - public void setOutfile(File outfile) { - this.outfile = outfile; - } - - /** Custom process name as the output EXE file name. */ - public boolean isCustomProcName() { - return customProcName; - } - - public void setCustomProcName(boolean customProcName) { - this.customProcName = customProcName; - } - - /** Splash screen configuration. */ - public Splash getSplash() { - return splash; - } - - public void setSplash(Splash splash) { - this.splash = splash; - } - - /** Stay alive after launching the application. */ - public boolean isStayAlive() { - return stayAlive; - } - - public void setStayAlive(boolean stayAlive) { - this.stayAlive = stayAlive; - } - - public VersionInfo getVersionInfo() { - return versionInfo; - } - - public void setVersionInfo(VersionInfo versionInfo) { - this.versionInfo = versionInfo; - } - - public boolean isDontWrapJar() { - return dontWrapJar; - } - - public void setDontWrapJar(boolean dontWrapJar) { - this.dontWrapJar = dontWrapJar; - } - - public int getPriorityIndex() { - int x = Arrays.asList(PRIORITY_CLASS_NAMES).indexOf(getPriority()); - return x != -1 ? x : 0; - } - - public void setPriorityIndex(int x) { - priority = PRIORITY_CLASS_NAMES[x]; - } - - public String getPriority() { - return Validator.isEmpty(priority) ? PRIORITY_CLASS_NAMES[0] : priority; - } - - public void setPriority(String priority) { - this.priority = priority; - } - - public int getPriorityClass() { - return PRIORITY_CLASSES[getPriorityIndex()]; - } - - public String getDownloadUrl() { - return downloadUrl == null ? DOWNLOAD_URL : downloadUrl; - } - - public void setDownloadUrl(String downloadUrl) { - this.downloadUrl = downloadUrl; - } - - public String getSupportUrl() { - return supportUrl; - } - - public void setSupportUrl(String supportUrl) { - this.supportUrl = supportUrl; - } - - public Msg getMessages() { - return messages; - } - - public void setMessages(Msg messages) { - this.messages = messages; - } - - public SingleInstance getSingleInstance() { - return singleInstance; - } - - public void setSingleInstance(SingleInstance singleInstance) { - this.singleInstance = singleInstance; - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/config/ConfigPersister.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/config/ConfigPersister.java deleted file mode 100755 index 43daf86814f..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/config/ConfigPersister.java +++ /dev/null @@ -1,249 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on Apr 22, 2005 - */ -package net.sf.launch4j.config; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import net.sf.launch4j.Util; - -import com.thoughtworks.xstream.XStream; -import com.thoughtworks.xstream.io.xml.DomDriver; - -/** - * @author Copyright (C) 2005 Grzegorz Kowal - */ -public class ConfigPersister { - - private static final ConfigPersister _instance = new ConfigPersister(); - - private final XStream _xstream; - private Config _config; - private File _configPath; - - private ConfigPersister() { - _xstream = new XStream(new DomDriver()); - _xstream.alias("launch4jConfig", Config.class); - _xstream.alias("classPath", ClassPath.class); - _xstream.alias("jre", Jre.class); - _xstream.alias("splash", Splash.class); - _xstream.alias("versionInfo", VersionInfo.class); - - _xstream.addImplicitCollection(Config.class, "headerObjects", "obj", - String.class); - _xstream.addImplicitCollection(Config.class, "libs", "lib", String.class); - _xstream.addImplicitCollection(Config.class, "variables", "var", String.class); - _xstream.addImplicitCollection(ClassPath.class, "paths", "cp", String.class); - _xstream.addImplicitCollection(Jre.class, "options", "opt", String.class); - } - - public static ConfigPersister getInstance() { - return _instance; - } - - public Config getConfig() { - return _config; - } - - public File getConfigPath() { - return _configPath; - } - - public File getOutputPath() throws IOException { - if (_config.getOutfile().isAbsolute()) { - return _config.getOutfile().getParentFile(); - } - File parent = _config.getOutfile().getParentFile(); - return (parent != null) ? new File(_configPath, parent.getPath()) : _configPath; - } - - public File getOutputFile() throws IOException { - return _config.getOutfile().isAbsolute() - ? _config.getOutfile() - : new File(getOutputPath(), _config.getOutfile().getName()); - } - - public void createBlank() { - _config = new Config(); - _config.setJre(new Jre()); - _configPath = null; - } - - public void setAntConfig(Config c, File basedir) { - _config = c; - _configPath = basedir; - } - - public void load(File f) throws ConfigPersisterException { - try { - FileReader r = new FileReader(f); - char[] buf = new char[(int) f.length()]; - r.read(buf); - r.close(); - // Convert 2.x config to 3.x - String s = String.valueOf(buf) - .replaceAll("0<", "gui<") - .replaceAll("1<", "console<") - .replaceAll("jarArgs>", "cmdLine>") - .replaceAll("", "") - .replaceAll("args>", "opt>") - .replaceAll("", "") - .replaceAll("false", - "" + Jre.JDK_PREFERENCE_PREFER_JRE + "") - .replaceAll("true", - "" + Jre.JDK_PREFERENCE_JRE_ONLY + "") - .replaceAll("0", "") - .replaceAll("0", ""); - _config = (Config) _xstream.fromXML(s); - setConfigPath(f); - } catch (Exception e) { - throw new ConfigPersisterException(e); - } - } - - /** - * Imports launch4j 1.x.x config file. - */ - public void loadVersion1(File f) throws ConfigPersisterException { - try { - Props props = new Props(f); - _config = new Config(); - String header = props.getProperty(Config.HEADER); - _config.setHeaderType(header == null - || header.toLowerCase().equals("guihead.bin") ? Config.GUI_HEADER - : Config.CONSOLE_HEADER); - _config.setJar(props.getFile(Config.JAR)); - _config.setOutfile(props.getFile(Config.OUTFILE)); - _config.setJre(new Jre()); - _config.getJre().setPath(props.getProperty(Jre.PATH)); - _config.getJre().setMinVersion(props.getProperty(Jre.MIN_VERSION)); - _config.getJre().setMaxVersion(props.getProperty(Jre.MAX_VERSION)); - String args = props.getProperty(Jre.ARGS); - if (args != null) { - List jreOptions = new ArrayList(); - jreOptions.add(args); - _config.getJre().setOptions(jreOptions); - } - _config.setCmdLine(props.getProperty(Config.JAR_ARGS)); - _config.setChdir("true".equals(props.getProperty(Config.CHDIR)) - ? "." : null); - _config.setCustomProcName("true".equals( - props.getProperty("setProcName"))); // 1.x - _config.setStayAlive("true".equals(props.getProperty(Config.STAY_ALIVE))); - _config.setErrTitle(props.getProperty(Config.ERR_TITLE)); - _config.setIcon(props.getFile(Config.ICON)); - File splashFile = props.getFile(Splash.SPLASH_FILE); - if (splashFile != null) { - _config.setSplash(new Splash()); - _config.getSplash().setFile(splashFile); - String waitfor = props.getProperty("waitfor"); // 1.x - _config.getSplash().setWaitForWindow(waitfor != null - && !waitfor.equals("")); - String splashTimeout = props.getProperty(Splash.TIMEOUT); - if (splashTimeout != null) { - _config.getSplash().setTimeout(Integer.parseInt(splashTimeout)); - } - _config.getSplash().setTimeoutErr("true".equals( - props.getProperty(Splash.TIMEOUT_ERR))); - } else { - _config.setSplash(null); - } - setConfigPath(f); - } catch (IOException e) { - throw new ConfigPersisterException(e); - } - } - - public void save(File f) throws ConfigPersisterException { - try { - BufferedWriter w = new BufferedWriter(new FileWriter(f)); - _xstream.toXML(_config, w); - w.close(); - setConfigPath(f); - } catch (Exception e) { - throw new ConfigPersisterException(e); - } - } - - private void setConfigPath(File configFile) { - _configPath = configFile.getAbsoluteFile().getParentFile(); - } - - private class Props { - final Properties _properties = new Properties(); - - public Props(File f) throws IOException { - FileInputStream is = null; - try { - is = new FileInputStream(f); - _properties.load(is); - } finally { - Util.close(is); - } - } - - /** - * Get property and remove trailing # comments. - */ - public String getProperty(String key) { - String p = _properties.getProperty(key); - if (p == null) { - return null; - } - int x = p.indexOf('#'); - if (x == -1) { - return p; - } - do { - x--; - } while (x > 0 && (p.charAt(x) == ' ' || p.charAt(x) == '\t')); - return (x == 0) ? "" : p.substring(0, x + 1); - } - - public File getFile(String key) { - String value = getProperty(key); - return value != null ? new File(value) : null; - } - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/config/ConfigPersisterException.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/config/ConfigPersisterException.java deleted file mode 100755 index 29940b945ff..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/config/ConfigPersisterException.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on Apr 22, 2005 - */ -package net.sf.launch4j.config; - -/** - * @author Copyright (C) 2005 Grzegorz Kowal - */ -public class ConfigPersisterException extends Exception { - - public ConfigPersisterException(String msg, Throwable t) { - super(msg, t); - } - - public ConfigPersisterException(Throwable t) { - super(t); - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/config/Jre.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/config/Jre.java deleted file mode 100755 index 0df45bb84a7..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/config/Jre.java +++ /dev/null @@ -1,235 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on Apr 21, 2005 - */ -package net.sf.launch4j.config; - -import java.util.Arrays; -import java.util.List; - -import net.sf.launch4j.binding.IValidatable; -import net.sf.launch4j.binding.Validator; - -/** - * @author Copyright (C) 2005 Grzegorz Kowal - */ -public class Jre implements IValidatable { - - // 1.x config properties_____________________________________________________________ - public static final String PATH = "jrepath"; - public static final String MIN_VERSION = "javamin"; - public static final String MAX_VERSION = "javamax"; - public static final String ARGS = "jvmArgs"; - - // __________________________________________________________________________________ - public static final String VERSION_PATTERN = "(\\d\\.){2}\\d(_\\d+)?"; - - public static final String JDK_PREFERENCE_JRE_ONLY = "jreOnly"; - public static final String JDK_PREFERENCE_PREFER_JRE = "preferJre"; - public static final String JDK_PREFERENCE_PREFER_JDK = "preferJdk"; - public static final String JDK_PREFERENCE_JDK_ONLY = "jdkOnly"; - - private static final String[] JDK_PREFERENCE_NAMES = new String[] { - JDK_PREFERENCE_JRE_ONLY, - JDK_PREFERENCE_PREFER_JRE, - JDK_PREFERENCE_PREFER_JDK, - JDK_PREFERENCE_JDK_ONLY }; - - public static final int DEFAULT_JDK_PREFERENCE_INDEX - = Arrays.asList(JDK_PREFERENCE_NAMES).indexOf(JDK_PREFERENCE_PREFER_JRE); - - private String path; - private String minVersion; - private String maxVersion; - private String jdkPreference; - private Integer initialHeapSize; - private Integer initialHeapPercent; - private Integer maxHeapSize; - private Integer maxHeapPercent; - private List options; - - public void checkInvariants() { - Validator.checkOptString(minVersion, 10, VERSION_PATTERN, - "jre.minVersion", Messages.getString("Jre.min.version")); - Validator.checkOptString(maxVersion, 10, VERSION_PATTERN, - "jre.maxVersion", Messages.getString("Jre.max.version")); - if (Validator.isEmpty(path)) { - Validator.checkFalse(Validator.isEmpty(minVersion), - "jre.minVersion", Messages.getString("Jre.specify.jre.min.version.or.path")); - } else { - Validator.checkString(path, Validator.MAX_PATH, - "jre.path", Messages.getString("Jre.bundled.path")); - } - if (!Validator.isEmpty(maxVersion)) { - Validator.checkFalse(Validator.isEmpty(minVersion), - "jre.minVersion", Messages.getString("Jre.specify.min.version")); - Validator.checkTrue(minVersion.compareTo(maxVersion) < 0, - "jre.maxVersion", Messages.getString("Jre.max.greater.than.min")); - } - Validator.checkTrue(initialHeapSize == null || maxHeapSize != null, - "jre.maxHeapSize", Messages.getString("Jre.initial.and.max.heap")); - Validator.checkTrue(initialHeapSize == null || initialHeapSize.intValue() > 0, - "jre.initialHeapSize", Messages.getString("Jre.initial.heap")); - Validator.checkTrue(maxHeapSize == null || (maxHeapSize.intValue() - >= ((initialHeapSize != null) ? initialHeapSize.intValue() : 1)), - "jre.maxHeapSize", Messages.getString("Jre.max.heap")); - Validator.checkTrue(initialHeapPercent == null || maxHeapPercent != null, - "jre.maxHeapPercent", Messages.getString("Jre.initial.and.max.heap")); - if (initialHeapPercent != null) { - Validator.checkRange(initialHeapPercent.intValue(), 1, 100, - "jre.initialHeapPercent", - Messages.getString("Jre.initial.heap.percent")); - } - if (maxHeapPercent != null) { - Validator.checkRange(maxHeapPercent.intValue(), - initialHeapPercent != null ? initialHeapPercent.intValue() : 1, 100, - "jre.maxHeapPercent", - Messages.getString("Jre.max.heap.percent")); - } - Validator.checkIn(getJdkPreference(), JDK_PREFERENCE_NAMES, - "jre.jdkPreference", Messages.getString("Jre.jdkPreference.invalid")); - Validator.checkOptStrings(options, - Validator.MAX_ARGS, - Validator.MAX_ARGS, - "[^\"]*|([^\"]*\"[^\"]*\"[^\"]*)*", - "jre.options", - Messages.getString("Jre.jvm.options"), - Messages.getString("Jre.jvm.options.unclosed.quotation")); - - // Quoted variable references: "[^%]*|([^%]*\"([^%]*%[^%]+%[^%]*)+\"[^%]*)*" - Validator.checkOptStrings(options, - Validator.MAX_ARGS, - Validator.MAX_ARGS, - "[^%]*|([^%]*([^%]*%[^%]+%[^%]*)+[^%]*)*", - "jre.options", - Messages.getString("Jre.jvm.options"), - Messages.getString("Jre.jvm.options.variable")); - } - - /** JVM options */ - public List getOptions() { - return options; - } - - public void setOptions(List options) { - this.options = options; - } - - /** Max Java version (x.x.x) */ - public String getMaxVersion() { - return maxVersion; - } - - public void setMaxVersion(String maxVersion) { - this.maxVersion = maxVersion; - } - - /** Min Java version (x.x.x) */ - public String getMinVersion() { - return minVersion; - } - - public void setMinVersion(String minVersion) { - this.minVersion = minVersion; - } - - /** Preference for standalone JRE or JDK-private JRE */ - public String getJdkPreference() { - return Validator.isEmpty(jdkPreference) ? JDK_PREFERENCE_PREFER_JRE - : jdkPreference; - } - - public void setJdkPreference(String jdkPreference) { - this.jdkPreference = jdkPreference; - } - - /** Preference for standalone JRE or JDK-private JRE */ - public int getJdkPreferenceIndex() { - int x = Arrays.asList(JDK_PREFERENCE_NAMES).indexOf(getJdkPreference()); - return x != -1 ? x : DEFAULT_JDK_PREFERENCE_INDEX; - } - - public void setJdkPreferenceIndex(int x) { - jdkPreference = JDK_PREFERENCE_NAMES[x]; - } - - /** JRE path */ - public String getPath() { - return path; - } - - public void setPath(String path) { - this.path = path; - } - - /** Initial heap size in MB */ - public Integer getInitialHeapSize() { - return initialHeapSize; - } - - public void setInitialHeapSize(Integer initialHeapSize) { - this.initialHeapSize = getInteger(initialHeapSize); - } - - /** Max heap size in MB */ - public Integer getMaxHeapSize() { - return maxHeapSize; - } - - public void setMaxHeapSize(Integer maxHeapSize) { - this.maxHeapSize = getInteger(maxHeapSize); - } - - public Integer getInitialHeapPercent() { - return initialHeapPercent; - } - - public void setInitialHeapPercent(Integer initialHeapPercent) { - this.initialHeapPercent = getInteger(initialHeapPercent); - } - - public Integer getMaxHeapPercent() { - return maxHeapPercent; - } - - public void setMaxHeapPercent(Integer maxHeapPercent) { - this.maxHeapPercent = getInteger(maxHeapPercent); - } - - /** Convert 0 to null */ - private Integer getInteger(Integer i) { - return i != null && i.intValue() == 0 ? null : i; - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/config/LdDefaults.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/config/LdDefaults.java deleted file mode 100755 index 55f457cc3fc..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/config/LdDefaults.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on Sep 3, 2005 - */ -package net.sf.launch4j.config; - -import java.util.Arrays; -import java.util.List; - -public class LdDefaults { - - public static final List GUI_HEADER_OBJECTS = Arrays.asList(new String[] { - "w32api/crt2.o", - "head/guihead.o", - "head/head.o" }); - - public static final List CONSOLE_HEADER_OBJECTS = Arrays.asList(new String[] { - "w32api/crt2.o", - "head/consolehead.o", - "head/head.o"}); - - public static final List LIBS = Arrays.asList(new String[] { - "w32api/libmingw32.a", - "w32api/libgcc.a", - "w32api/libmsvcrt.a", - "w32api/libkernel32.a", - "w32api/libuser32.a", - "w32api/libadvapi32.a", - "w32api/libshell32.a" }); -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/config/Messages.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/config/Messages.java deleted file mode 100755 index a3f344e59c9..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/config/Messages.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -package net.sf.launch4j.config; - -import java.text.MessageFormat; -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -public class Messages { - private static final String BUNDLE_NAME = "net.sf.launch4j.config.messages"; - - private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle - .getBundle(BUNDLE_NAME); - private static final MessageFormat FORMATTER = new MessageFormat(""); - - private Messages() { - } - - public static String getString(String key) { - try { - return RESOURCE_BUNDLE.getString(key); - } catch (MissingResourceException e) { - return '!' + key + '!'; - } - } - - public static String getString(String key, String arg0) { - return getString(key, new Object[] {arg0}); - } - - public static String getString(String key, String arg0, String arg1) { - return getString(key, new Object[] {arg0, arg1}); - } - - public static String getString(String key, String arg0, String arg1, String arg2) { - return getString(key, new Object[] {arg0, arg1, arg2}); - } - - public static String getString(String key, Object[] args) { - try { - FORMATTER.applyPattern(RESOURCE_BUNDLE.getString(key)); - return FORMATTER.format(args); - } catch (MissingResourceException e) { - return '!' + key + '!'; - } - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/config/Msg.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/config/Msg.java deleted file mode 100755 index ea3acfa34d8..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/config/Msg.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on Oct 8, 2006 - */ -package net.sf.launch4j.config; - -import net.sf.launch4j.binding.IValidatable; -import net.sf.launch4j.binding.Validator; - -/** - * @author Copyright (C) 2006 Grzegorz Kowal - */ -public class Msg implements IValidatable { - private String startupErr; - private String bundledJreErr; - private String jreVersionErr; - private String launcherErr; - private String instanceAlreadyExistsMsg; - - public void checkInvariants() { - Validator.checkOptString(startupErr, 1024, "startupErr", - Messages.getString("Msg.startupErr")); - Validator.checkOptString(bundledJreErr, 1024, "bundledJreErr", - Messages.getString("Msg.bundledJreErr")); - Validator.checkOptString(jreVersionErr, 1024, "jreVersionErr", - Messages.getString("Msg.jreVersionErr")); - Validator.checkOptString(launcherErr, 1024, "launcherErr", - Messages.getString("Msg.launcherErr")); - Validator.checkOptString(instanceAlreadyExistsMsg, 1024, "instanceAlreadyExistsMsg", - Messages.getString("Msg.instanceAlreadyExistsMsg")); - } - - public String getStartupErr() { - return !Validator.isEmpty(startupErr) ? startupErr - : "An error occurred while starting the application."; - } - - public void setStartupErr(String startupErr) { - this.startupErr = startupErr; - } - - public String getBundledJreErr() { - return !Validator.isEmpty(bundledJreErr) ? bundledJreErr - : "This application was configured to use a bundled Java Runtime" + - " Environment but the runtime is missing or corrupted."; - } - - public void setBundledJreErr(String bundledJreErr) { - this.bundledJreErr = bundledJreErr; - } - - public String getJreVersionErr() { - return !Validator.isEmpty(jreVersionErr) ? jreVersionErr - : "This application requires a Java Runtime Environment"; - } - - public void setJreVersionErr(String jreVersionErr) { - this.jreVersionErr = jreVersionErr; - } - - public String getLauncherErr() { - return !Validator.isEmpty(launcherErr) ? launcherErr - : "The registry refers to a nonexistent Java Runtime Environment" + - " installation or the runtime is corrupted."; - } - - public void setLauncherErr(String launcherErr) { - this.launcherErr = launcherErr; - } - - public String getInstanceAlreadyExistsMsg() { - return !Validator.isEmpty(instanceAlreadyExistsMsg) ? instanceAlreadyExistsMsg - : "An application instance is already running."; - } - - public void setInstanceAlreadyExistsMsg(String instanceAlreadyExistsMsg) { - this.instanceAlreadyExistsMsg = instanceAlreadyExistsMsg; - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/config/SingleInstance.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/config/SingleInstance.java deleted file mode 100755 index 0ae340cd734..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/config/SingleInstance.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/** - * Created on 2007-09-16 - */ -package net.sf.launch4j.config; - -import net.sf.launch4j.binding.IValidatable; -import net.sf.launch4j.binding.Validator; - -/** - * @author Copyright (C) 2007 Grzegorz Kowal - */ -public class SingleInstance implements IValidatable { - - private String mutexName; - private String windowTitle; - - public void checkInvariants() { - Validator.checkString(mutexName, Validator.MAX_STR, - "singleInstance.mutexName", - Messages.getString("SingleInstance.mutexName")); - Validator.checkOptString(windowTitle, Validator.MAX_STR, - "singleInstance.windowTitle", - Messages.getString("SingleInstance.windowTitle")); - } - - public String getWindowTitle() { - return windowTitle; - } - - public void setWindowTitle(String appWindowName) { - this.windowTitle = appWindowName; - } - - public String getMutexName() { - return mutexName; - } - - public void setMutexName(String mutexName) { - this.mutexName = mutexName; - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/config/Splash.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/config/Splash.java deleted file mode 100755 index f736f82088e..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/config/Splash.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on Apr 21, 2005 - */ -package net.sf.launch4j.config; - -import java.io.File; - -import net.sf.launch4j.binding.IValidatable; -import net.sf.launch4j.binding.Validator; - -/** - * @author Copyright (C) 2005 Grzegorz Kowal - */ -public class Splash implements IValidatable { - - // 1.x config properties_____________________________________________________________ - public static final String SPLASH_FILE = "splash"; - public static final String WAIT_FOR_TITLE = "waitForTitle"; - public static final String TIMEOUT = "splashTimeout"; - public static final String TIMEOUT_ERR = "splashTimeoutErr"; - - // __________________________________________________________________________________ - private File file; - private boolean waitForWindow = true; - private int timeout = 60; - private boolean timeoutErr = true; - - public void checkInvariants() { - Validator.checkFile(file, "splash.file", - Messages.getString("Splash.splash.file")); - Validator.checkRange(timeout, 1, 60 * 15, "splash.timeout", - Messages.getString("Splash.splash.timeout")); - } - - /** Splash screen in BMP format. */ - public File getFile() { - return file; - } - - public void setFile(File file) { - this.file = file; - } - - /** Splash timeout in seconds. */ - public int getTimeout() { - return timeout; - } - - public void setTimeout(int timeout) { - this.timeout = timeout; - } - - /** Signal error on splash timeout. */ - public boolean isTimeoutErr() { - return timeoutErr; - } - - public void setTimeoutErr(boolean timeoutErr) { - this.timeoutErr = timeoutErr; - } - - /** Hide splash screen when the child process displayes the first window. */ - public boolean getWaitForWindow() { - return waitForWindow; - } - - public void setWaitForWindow(boolean waitForWindow) { - this.waitForWindow = waitForWindow; - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/config/VersionInfo.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/config/VersionInfo.java deleted file mode 100755 index d719460c2ab..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/config/VersionInfo.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on May 21, 2005 - */ -package net.sf.launch4j.config; - -import net.sf.launch4j.binding.IValidatable; -import net.sf.launch4j.binding.Validator; - -/** - * @author Copyright (C) 2005 Grzegorz Kowal - */ -public class VersionInfo implements IValidatable { - public static final String VERSION_PATTERN = "(\\d+\\.){3}\\d+"; - - private String fileVersion; - private String txtFileVersion; - private String fileDescription; - private String copyright; - private String productVersion; - private String txtProductVersion; - private String productName; - private String companyName; - private String internalName; - private String originalFilename; - - public void checkInvariants() { - Validator.checkString(fileVersion, 20, VERSION_PATTERN, - "versionInfo.fileVersion", - Messages.getString("VersionInfo.file.version")); - Validator.checkString(txtFileVersion, 50, "versionInfo.txtFileVersion", - Messages.getString("VersionInfo.txt.file.version")); - Validator.checkString(fileDescription, 150, "versionInfo.fileDescription", - Messages.getString("VersionInfo.file.description")); - Validator.checkString(copyright, 150, "versionInfo.copyright", - Messages.getString("VersionInfo.copyright")); - Validator.checkString(productVersion, 20, VERSION_PATTERN, - "versionInfo.productVersion", - Messages.getString("VersionInfo.product.version")); - Validator.checkString(txtProductVersion, 50, "versionInfo.txtProductVersion", - Messages.getString("VersionInfo.txt.product.version")); - Validator.checkString(productName, 150, "versionInfo.productName", - Messages.getString("VersionInfo.product.name")); - Validator.checkOptString(companyName, 150, "versionInfo.companyName", - Messages.getString("VersionInfo.company.name")); - Validator.checkString(internalName, 50, "versionInfo.internalName", - Messages.getString("VersionInfo.internal.name")); - Validator.checkTrue(!internalName.endsWith(".exe"), "versionInfo.internalName", - Messages.getString("VersionInfo.internal.name.not.exe")); - Validator.checkString(originalFilename, 50, "versionInfo.originalFilename", - Messages.getString("VersionInfo.original.filename")); - Validator.checkTrue(originalFilename.endsWith(".exe"), - "versionInfo.originalFilename", - Messages.getString("VersionInfo.original.filename.exe")); - } - - public String getCompanyName() { - return companyName; - } - - public void setCompanyName(String companyName) { - this.companyName = companyName; - } - - public String getCopyright() { - return copyright; - } - - public void setCopyright(String copyright) { - this.copyright = copyright; - } - - public String getFileDescription() { - return fileDescription; - } - - public void setFileDescription(String fileDescription) { - this.fileDescription = fileDescription; - } - - public String getFileVersion() { - return fileVersion; - } - - public void setFileVersion(String fileVersion) { - this.fileVersion = fileVersion; - } - - public String getInternalName() { - return internalName; - } - - public void setInternalName(String internalName) { - this.internalName = internalName; - } - - public String getOriginalFilename() { - return originalFilename; - } - - public void setOriginalFilename(String originalFilename) { - this.originalFilename = originalFilename; - } - - public String getProductName() { - return productName; - } - - public void setProductName(String productName) { - this.productName = productName; - } - - public String getProductVersion() { - return productVersion; - } - - public void setProductVersion(String productVersion) { - this.productVersion = productVersion; - } - - public String getTxtFileVersion() { - return txtFileVersion; - } - - public void setTxtFileVersion(String txtFileVersion) { - this.txtFileVersion = txtFileVersion; - } - - public String getTxtProductVersion() { - return txtProductVersion; - } - - public void setTxtProductVersion(String txtProductVersion) { - this.txtProductVersion = txtProductVersion; - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/config/messages.properties b/build/windows/launcher/launch4j/src/net/sf/launch4j/config/messages.properties deleted file mode 100755 index 5753663f48a..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/config/messages.properties +++ /dev/null @@ -1,93 +0,0 @@ -# -# Launch4j (http://launch4j.sourceforge.net/) -# Cross-platform Java application wrapper for creating Windows native executables. -# -# Copyright (c) 2004, 2007 Grzegorz Kowal -# -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without modification, -# are permitted provided that the following conditions are met: -# -# * Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# * Neither the name of the Launch4j nor the names of its contributors -# may be used to endorse or promote products derived from this software without -# specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# - -Splash.splash.file=Splash file -Splash.splash.timeout=Splash timeout - -Config.specify.output.exe=Specify output file with .exe extension. -Config.application.jar=Application jar -Config.application.jar.path=Specify runtime path of the jar relative to the executable. -Config.chdir.relative='chdir' must be a path relative to the executable. -Config.chdir.path='chdir' is now a path instead of a boolean, please check the docs. -Config.manifest=Manifest -Config.icon=Icon -Config.jar.arguments=Jar arguments -Config.error.title=Error title -Config.download.url=Download URL -Config.support.url=Support URL -Config.header.type=Header type -Config.splash.not.impl.by.console.hdr=Splash screen is not implemented by console header. -Config.variables=Environment variables -Config.variables.err=Environment variable assignment should have the form varname=[value][%varref%]... -Config.priority=Process priority - -ClassPath.mainClass=Main class -ClassPath.or.jar=Specify runtime path of a jar or the classpath. -ClassPath.path=Classpath - -VersionInfo.file.version=File version, should be 'x.x.x.x' -VersionInfo.txt.file.version=Free form file version -VersionInfo.file.description=File description -VersionInfo.copyright=Copyright -VersionInfo.product.version=Product version, should be 'x.x.x.x' -VersionInfo.txt.product.version=Free from product version -VersionInfo.product.name=Product name -VersionInfo.company.name=Company name -VersionInfo.internal.name=Internal name -VersionInfo.internal.name.not.exe=Internal name shouldn't have the .exe extension. -VersionInfo.original.filename=Original filename -VersionInfo.original.filename.exe=Original filename should end with the .exe extension. - -Jre.min.version=Minimum JRE version should be x.x.x[_xx] -Jre.max.version=Maximum JRE version should be x.x.x[_xx] -Jre.specify.jre.min.version.or.path=Specify minimum JRE version and/or bundled JRE path. -Jre.bundled.path=Bundled JRE path -Jre.specify.min.version=Specify minimum JRE version. -Jre.max.greater.than.min=Maximum JRE version must be greater than the minimum.\nTo use a certain JRE version, you may set the min/max range to [1.4.2 - 1.4.2_10] for example. -Jre.initial.and.max.heap=If you change the initial heap size please also specify the maximum size. -Jre.initial.heap=Initial heap size must be greater than 0, leave the field blank to use the JVM default. -Jre.max.heap=Maximum heap size cannot be less than the initial size, leave the field blank to use the JVM default. -Jre.initial.heap.percent=Initial heap % -Jre.max.heap.percent=Maximum heap % -Jre.jdkPreference.invalid=Unrecognised value for JDK preference, should be between 0 and 3 inclusive. -Jre.jvm.options=JVM arguments -Jre.jvm.options.unclosed.quotation=JVM arguments contain an unclosed quotation. -Jre.jvm.options.variable=Invalid environment variable reference. - -Msg.startupErr=Startup error message -Msg.bundledJreErr=Bundled JRE error message -Msg.jreVersionErr=JRE version error message -Msg.launcherErr=Launcher error message - -SingleInstance.mutexName=Mutex name -SingleInstance.windowTitle=Window title diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/config/messages_es.properties b/build/windows/launcher/launch4j/src/net/sf/launch4j/config/messages_es.properties deleted file mode 100755 index 5e8659b1fea..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/config/messages_es.properties +++ /dev/null @@ -1,75 +0,0 @@ -# -# Launch4j (http://launch4j.sourceforge.net/) -# Cross-platform Java application wrapper for creating Windows native executables. -# -# Copyright (c) 2004, 2007 Grzegorz Kowal, Patricio Mart�nez Ros -# -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without modification, -# are permitted provided that the following conditions are met: -# -# * Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# * Neither the name of the Launch4j nor the names of its contributors -# may be used to endorse or promote products derived from this software without -# specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# - -Splash.splash.file = Fichero de la pantalla de bienvenida -Splash.splash.timeout = Tiempo de espera de la pantalla de bienvenida - -Config.specify.output.exe = Especifique el fichero de salida con extensi\u00F3n .exe. -Config.application.jar = Aplicaci\u00F3n jar -Config.application.jar.path = Especifique la ruta del jar relativa al ejecutable. -Config.chdir.relative = 'Cambiar al directorio' debe ser una ruta relativa al ejecutable. -Config.chdir.path = 'Cambiar al directorio' ahora es una ruta en lugar de un booleano, por favor consulte la documentaci\u00F3n. -Config.icon = Icono -Config.jar.arguments = Argumentos del jar -Config.error.title = T\u00EDtulo de error -Config.header.type = Tipo de cabecera -Config.splash.not.impl.by.console.hdr = La pantalla de bienvenida no est\u00E1 implementada para la cabecera de tipo consola. - -VersionInfo.file.version = La versi\u00F3n del fichero, deber\u00EDa ser 'x.x.x.x' -VersionInfo.txt.file.version = Forma libre de versi\u00F3n del fichero -VersionInfo.file.description = Descripci\u00F3n del fichero -VersionInfo.copyright = Copyright -VersionInfo.product.version = Versi\u00F3n del producto, deber\u00EDa ser 'x.x.x.x' -VersionInfo.txt.product.version = Forma libre de versi\u00F3n del producto -VersionInfo.product.name = Nombre del producto -VersionInfo.company.name = Nombre de la organizaci\u00F3n -VersionInfo.internal.name = Nombre interno -VersionInfo.internal.name.not.exe = El nombre interno no deber\u00EDa tener extensi\u00F3n .exe. -VersionInfo.original.filename = Nombre original del fichero -VersionInfo.original.filename.exe = El nombre original del fichero debe acabar con extensi\u00F3n .exe. -Jre.min.version = La versi\u00F3n m\u00EDnima del JRE deber\u00EDa ser x.x.x[_xx] -Jre.max.version = La versi\u00F3n m\u00E1xima del JRE deber\u00EDa ser x.x.x[_xx] -Jre.specify.jre.min.version.or.path=Specify minimum JRE version and/or bundled JRE path. -Jre.bundled.path.rel = La ruta del JRE debe ser relativa al ejecutable. -Jre.specify.min.version = Especifique la versi\u00F3n m\u00EDnima del JRE. -Jre.max.greater.than.min = La versi\u00F3n m\u00E1xima del JRE debe ser mayor que la m\u00EDnima.\nPara usar cierta versi\u00F3n del JRE, puede esyablecer el rango m\u00EDnimo/m\u00E1ximo a [1.4.2 - 1.4.2_10], por ejemplo. -Jre.jvm.options = Argumentos de la JVM - -Msg.startupErr=Startup error message -Msg.bundledJreErr=Bundled JRE error message -Msg.jreVersionErr=JRE version error message -Msg.launcherErr=Launcher error message - -SingleInstance.mutexName=Mutex name -SingleInstance.windowTitle=Window title - diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/BasicForm.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/form/BasicForm.java deleted file mode 100755 index 4dadbb98340..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/BasicForm.java +++ /dev/null @@ -1,283 +0,0 @@ -package net.sf.launch4j.form; - -import com.jeta.forms.components.separator.TitledSeparator; -import com.jgoodies.forms.layout.CellConstraints; -import com.jgoodies.forms.layout.FormLayout; -import java.awt.BorderLayout; -import java.awt.Container; -import java.awt.Dimension; -import javax.swing.Box; -import javax.swing.ButtonGroup; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JRadioButton; -import javax.swing.JTextField; - -public abstract class BasicForm extends JPanel -{ - protected final JButton _outfileButton = new JButton(); - protected final JLabel _outfileLabel = new JLabel(); - protected final JLabel _iconLabel = new JLabel(); - protected final JLabel _jarLabel = new JLabel(); - protected final JButton _jarButton = new JButton(); - protected final JButton _iconButton = new JButton(); - protected final JLabel _cmdLineLabel = new JLabel(); - protected final JLabel _optionsLabel = new JLabel(); - protected final JLabel _chdirLabel = new JLabel(); - protected final JLabel _processPriorityLabel = new JLabel(); - protected final JRadioButton _normalPriorityRadio = new JRadioButton(); - protected final ButtonGroup _buttongroup1 = new ButtonGroup(); - protected final JRadioButton _idlePriorityRadio = new JRadioButton(); - protected final JRadioButton _highPriorityRadio = new JRadioButton(); - protected final JCheckBox _customProcNameCheck = new JCheckBox(); - protected final JCheckBox _stayAliveCheck = new JCheckBox(); - protected final JTextField _cmdLineField = new JTextField(); - protected final JTextField _chdirField = new JTextField(); - protected final JTextField _iconField = new JTextField(); - protected final JCheckBox _dontWrapJarCheck = new JCheckBox(); - protected final JTextField _jarField = new JTextField(); - protected final JTextField _outfileField = new JTextField(); - protected final JLabel _errorTitleLabel = new JLabel(); - protected final JTextField _errorTitleField = new JTextField(); - protected final JLabel _downloadUrlLabel = new JLabel(); - protected final JTextField _downloadUrlField = new JTextField(); - protected final JLabel _supportUrlLabel = new JLabel(); - protected final JTextField _supportUrlField = new JTextField(); - protected final JTextField _manifestField = new JTextField(); - protected final JButton _manifestButton = new JButton(); - - /** - * Default constructor - */ - public BasicForm() - { - initializePanel(); - } - - /** - * Adds fill components to empty cells in the first row and first column of the grid. - * This ensures that the grid spacing will be the same as shown in the designer. - * @param cols an array of column indices in the first row where fill components should be added. - * @param rows an array of row indices in the first column where fill components should be added. - */ - void addFillComponents( Container panel, int[] cols, int[] rows ) - { - Dimension filler = new Dimension(10,10); - - boolean filled_cell_11 = false; - CellConstraints cc = new CellConstraints(); - if ( cols.length > 0 && rows.length > 0 ) - { - if ( cols[0] == 1 && rows[0] == 1 ) - { - /** add a rigid area */ - panel.add( Box.createRigidArea( filler ), cc.xy(1,1) ); - filled_cell_11 = true; - } - } - - for( int index = 0; index < cols.length; index++ ) - { - if ( cols[index] == 1 && filled_cell_11 ) - { - continue; - } - panel.add( Box.createRigidArea( filler ), cc.xy(cols[index],1) ); - } - - for( int index = 0; index < rows.length; index++ ) - { - if ( rows[index] == 1 && filled_cell_11 ) - { - continue; - } - panel.add( Box.createRigidArea( filler ), cc.xy(1,rows[index]) ); - } - - } - - /** - * Helper method to load an image file from the CLASSPATH - * @param imageName the package and name of the file to load relative to the CLASSPATH - * @return an ImageIcon instance with the specified image file - * @throws IllegalArgumentException if the image resource cannot be loaded. - */ - public ImageIcon loadImage( String imageName ) - { - try - { - ClassLoader classloader = getClass().getClassLoader(); - java.net.URL url = classloader.getResource( imageName ); - if ( url != null ) - { - ImageIcon icon = new ImageIcon( url ); - return icon; - } - } - catch( Exception e ) - { - e.printStackTrace(); - } - throw new IllegalArgumentException( "Unable to load image: " + imageName ); - } - - public JPanel createPanel() - { - JPanel jpanel1 = new JPanel(); - FormLayout formlayout1 = new FormLayout("FILL:7DLU:NONE,RIGHT:MAX(65DLU;DEFAULT):NONE,FILL:3DLU:NONE,FILL:DEFAULT:NONE,FILL:7DLU:NONE,FILL:DEFAULT:NONE,FILL:7DLU:NONE,FILL:DEFAULT:NONE,FILL:DEFAULT:NONE,FILL:DEFAULT:GROW(1.0),FILL:3DLU:NONE,FILL:26PX:NONE,FILL:7DLU:NONE","CENTER:9DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:9DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:9DLU:NONE"); - CellConstraints cc = new CellConstraints(); - jpanel1.setLayout(formlayout1); - - _outfileButton.setIcon(loadImage("images/open16.png")); - _outfileButton.setName("outfileButton"); - jpanel1.add(_outfileButton,cc.xy(12,2)); - - _outfileLabel.setIcon(loadImage("images/asterix.gif")); - _outfileLabel.setName("outfileLabel"); - _outfileLabel.setText(Messages.getString("outfile")); - jpanel1.add(_outfileLabel,cc.xy(2,2)); - - _iconLabel.setName("iconLabel"); - _iconLabel.setText(Messages.getString("icon")); - jpanel1.add(_iconLabel,cc.xy(2,10)); - - _jarLabel.setIcon(loadImage("images/asterix.gif")); - _jarLabel.setName("jarLabel"); - _jarLabel.setText(Messages.getString("jar")); - jpanel1.add(_jarLabel,cc.xy(2,4)); - - _jarButton.setIcon(loadImage("images/open16.png")); - _jarButton.setName("jarButton"); - jpanel1.add(_jarButton,cc.xy(12,4)); - - _iconButton.setIcon(loadImage("images/open16.png")); - _iconButton.setName("iconButton"); - jpanel1.add(_iconButton,cc.xy(12,10)); - - _cmdLineLabel.setName("cmdLineLabel"); - _cmdLineLabel.setText(Messages.getString("cmdLine")); - _cmdLineLabel.setToolTipText(""); - jpanel1.add(_cmdLineLabel,cc.xy(2,14)); - - _optionsLabel.setName("optionsLabel"); - _optionsLabel.setText(Messages.getString("options")); - jpanel1.add(_optionsLabel,cc.xy(2,18)); - - _chdirLabel.setName("chdirLabel"); - _chdirLabel.setText(Messages.getString("chdir")); - jpanel1.add(_chdirLabel,cc.xy(2,12)); - - _processPriorityLabel.setName("processPriorityLabel"); - _processPriorityLabel.setText(Messages.getString("priority")); - jpanel1.add(_processPriorityLabel,cc.xy(2,16)); - - _normalPriorityRadio.setActionCommand(Messages.getString("normalPriority")); - _normalPriorityRadio.setName("normalPriorityRadio"); - _normalPriorityRadio.setText(Messages.getString("normalPriority")); - _buttongroup1.add(_normalPriorityRadio); - jpanel1.add(_normalPriorityRadio,cc.xy(4,16)); - - _idlePriorityRadio.setActionCommand(Messages.getString("idlePriority")); - _idlePriorityRadio.setName("idlePriorityRadio"); - _idlePriorityRadio.setText(Messages.getString("idlePriority")); - _buttongroup1.add(_idlePriorityRadio); - jpanel1.add(_idlePriorityRadio,cc.xy(6,16)); - - _highPriorityRadio.setActionCommand(Messages.getString("highPriority")); - _highPriorityRadio.setName("highPriorityRadio"); - _highPriorityRadio.setText(Messages.getString("highPriority")); - _buttongroup1.add(_highPriorityRadio); - jpanel1.add(_highPriorityRadio,cc.xy(8,16)); - - _customProcNameCheck.setActionCommand("Custom process name"); - _customProcNameCheck.setName("customProcNameCheck"); - _customProcNameCheck.setText(Messages.getString("customProcName")); - jpanel1.add(_customProcNameCheck,cc.xywh(4,18,7,1)); - - _stayAliveCheck.setActionCommand("Stay alive after launching a GUI application"); - _stayAliveCheck.setName("stayAliveCheck"); - _stayAliveCheck.setText(Messages.getString("stayAlive")); - jpanel1.add(_stayAliveCheck,cc.xywh(4,20,7,1)); - - _cmdLineField.setName("cmdLineField"); - _cmdLineField.setToolTipText(Messages.getString("cmdLineTip")); - jpanel1.add(_cmdLineField,cc.xywh(4,14,7,1)); - - _chdirField.setName("chdirField"); - _chdirField.setToolTipText(Messages.getString("chdirTip")); - jpanel1.add(_chdirField,cc.xywh(4,12,7,1)); - - _iconField.setName("iconField"); - _iconField.setToolTipText(Messages.getString("iconTip")); - jpanel1.add(_iconField,cc.xywh(4,10,7,1)); - - _dontWrapJarCheck.setActionCommand("Don't wrap the jar, launch it only"); - _dontWrapJarCheck.setName("dontWrapJarCheck"); - _dontWrapJarCheck.setText(Messages.getString("dontWrapJar")); - jpanel1.add(_dontWrapJarCheck,cc.xywh(4,6,7,1)); - - _jarField.setName("jarField"); - _jarField.setToolTipText(Messages.getString("jarTip")); - jpanel1.add(_jarField,cc.xywh(4,4,7,1)); - - _outfileField.setName("outfileField"); - _outfileField.setToolTipText(Messages.getString("outfileTip")); - jpanel1.add(_outfileField,cc.xywh(4,2,7,1)); - - TitledSeparator titledseparator1 = new TitledSeparator(); - titledseparator1.setText(Messages.getString("downloadAndSupport")); - jpanel1.add(titledseparator1,cc.xywh(2,22,11,1)); - - _errorTitleLabel.setName("errorTitleLabel"); - _errorTitleLabel.setText(Messages.getString("errorTitle")); - jpanel1.add(_errorTitleLabel,cc.xy(2,24)); - - _errorTitleField.setName("errorTitleField"); - _errorTitleField.setToolTipText(Messages.getString("errorTitleTip")); - jpanel1.add(_errorTitleField,cc.xywh(4,24,7,1)); - - _downloadUrlLabel.setIcon(loadImage("images/asterix.gif")); - _downloadUrlLabel.setName("downloadUrlLabel"); - _downloadUrlLabel.setText(Messages.getString("downloadUrl")); - jpanel1.add(_downloadUrlLabel,cc.xy(2,26)); - - _downloadUrlField.setName("downloadUrlField"); - jpanel1.add(_downloadUrlField,cc.xywh(4,26,7,1)); - - _supportUrlLabel.setName("supportUrlLabel"); - _supportUrlLabel.setText(Messages.getString("supportUrl")); - jpanel1.add(_supportUrlLabel,cc.xy(2,28)); - - _supportUrlField.setName("supportUrlField"); - jpanel1.add(_supportUrlField,cc.xywh(4,28,7,1)); - - JLabel jlabel1 = new JLabel(); - jlabel1.setText(Messages.getString("manifest")); - jpanel1.add(jlabel1,cc.xy(2,8)); - - _manifestField.setName("manifestField"); - _manifestField.setToolTipText(Messages.getString("manifestTip")); - jpanel1.add(_manifestField,cc.xywh(4,8,7,1)); - - _manifestButton.setIcon(loadImage("images/open16.png")); - _manifestButton.setName("manifestButton"); - jpanel1.add(_manifestButton,cc.xy(12,8)); - - addFillComponents(jpanel1,new int[]{ 1,2,3,4,5,6,7,8,9,10,11,12,13 },new int[]{ 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29 }); - return jpanel1; - } - - /** - * Initializer - */ - protected void initializePanel() - { - setLayout(new BorderLayout()); - add(createPanel(), BorderLayout.CENTER); - } - - -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/BasicForm.jfrm b/build/windows/launcher/launch4j/src/net/sf/launch4j/form/BasicForm.jfrm deleted file mode 100755 index 1d8a9ad58d7..00000000000 Binary files a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/BasicForm.jfrm and /dev/null differ diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/ClassPathForm.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/form/ClassPathForm.java deleted file mode 100755 index 9f4f5247114..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/ClassPathForm.java +++ /dev/null @@ -1,193 +0,0 @@ -package net.sf.launch4j.form; - -import com.jgoodies.forms.layout.CellConstraints; -import com.jgoodies.forms.layout.FormLayout; -import java.awt.BorderLayout; -import java.awt.Container; -import java.awt.Dimension; -import javax.swing.Box; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextField; - -public abstract class ClassPathForm extends JPanel -{ - protected final JTextField _classpathField = new JTextField(); - protected final JLabel _classpathFieldLabel = new JLabel(); - protected final JLabel _classpathListLabel = new JLabel(); - protected final JList _classpathList = new JList(); - protected final JLabel _mainclassLabel = new JLabel(); - protected final JTextField _mainclassField = new JTextField(); - protected final JButton _acceptClasspathButton = new JButton(); - protected final JButton _removeClasspathButton = new JButton(); - protected final JButton _importClasspathButton = new JButton(); - protected final JButton _classpathUpButton = new JButton(); - protected final JButton _classpathDownButton = new JButton(); - protected final JCheckBox _classpathCheck = new JCheckBox(); - protected final JButton _newClasspathButton = new JButton(); - - /** - * Default constructor - */ - public ClassPathForm() - { - initializePanel(); - } - - /** - * Adds fill components to empty cells in the first row and first column of the grid. - * This ensures that the grid spacing will be the same as shown in the designer. - * @param cols an array of column indices in the first row where fill components should be added. - * @param rows an array of row indices in the first column where fill components should be added. - */ - void addFillComponents( Container panel, int[] cols, int[] rows ) - { - Dimension filler = new Dimension(10,10); - - boolean filled_cell_11 = false; - CellConstraints cc = new CellConstraints(); - if ( cols.length > 0 && rows.length > 0 ) - { - if ( cols[0] == 1 && rows[0] == 1 ) - { - /** add a rigid area */ - panel.add( Box.createRigidArea( filler ), cc.xy(1,1) ); - filled_cell_11 = true; - } - } - - for( int index = 0; index < cols.length; index++ ) - { - if ( cols[index] == 1 && filled_cell_11 ) - { - continue; - } - panel.add( Box.createRigidArea( filler ), cc.xy(cols[index],1) ); - } - - for( int index = 0; index < rows.length; index++ ) - { - if ( rows[index] == 1 && filled_cell_11 ) - { - continue; - } - panel.add( Box.createRigidArea( filler ), cc.xy(1,rows[index]) ); - } - - } - - /** - * Helper method to load an image file from the CLASSPATH - * @param imageName the package and name of the file to load relative to the CLASSPATH - * @return an ImageIcon instance with the specified image file - * @throws IllegalArgumentException if the image resource cannot be loaded. - */ - public ImageIcon loadImage( String imageName ) - { - try - { - ClassLoader classloader = getClass().getClassLoader(); - java.net.URL url = classloader.getResource( imageName ); - if ( url != null ) - { - ImageIcon icon = new ImageIcon( url ); - return icon; - } - } - catch( Exception e ) - { - e.printStackTrace(); - } - throw new IllegalArgumentException( "Unable to load image: " + imageName ); - } - - public JPanel createPanel() - { - JPanel jpanel1 = new JPanel(); - FormLayout formlayout1 = new FormLayout("FILL:7DLU:NONE,RIGHT:MAX(65DLU;DEFAULT):NONE,FILL:3DLU:NONE,FILL:DEFAULT:GROW(1.0),FILL:3DLU:NONE,FILL:DEFAULT:NONE,FILL:3DLU:NONE,FILL:DEFAULT:NONE,FILL:3DLU:NONE,FILL:DEFAULT:NONE,FILL:3DLU:NONE,FILL:26PX:NONE,FILL:7DLU:NONE","CENTER:9DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:DEFAULT:GROW(1.0),CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:9DLU:NONE"); - CellConstraints cc = new CellConstraints(); - jpanel1.setLayout(formlayout1); - - _classpathField.setName("classpathField"); - jpanel1.add(_classpathField,cc.xywh(4,11,7,1)); - - _classpathFieldLabel.setIcon(loadImage("images/asterix.gif")); - _classpathFieldLabel.setName("classpathFieldLabel"); - _classpathFieldLabel.setText(Messages.getString("editClassPath")); - jpanel1.add(_classpathFieldLabel,cc.xy(2,11)); - - _classpathListLabel.setName("classpathListLabel"); - _classpathListLabel.setText(Messages.getString("classPath")); - jpanel1.add(_classpathListLabel,cc.xy(2,6)); - - _classpathList.setName("classpathList"); - JScrollPane jscrollpane1 = new JScrollPane(); - jscrollpane1.setViewportView(_classpathList); - jscrollpane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); - jscrollpane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - jpanel1.add(jscrollpane1,cc.xywh(4,6,7,4)); - - _mainclassLabel.setIcon(loadImage("images/asterix.gif")); - _mainclassLabel.setName("mainclassLabel"); - _mainclassLabel.setText(Messages.getString("mainClass")); - jpanel1.add(_mainclassLabel,cc.xy(2,4)); - - _mainclassField.setName("mainclassField"); - jpanel1.add(_mainclassField,cc.xywh(4,4,7,1)); - - _acceptClasspathButton.setActionCommand("Add"); - _acceptClasspathButton.setIcon(loadImage("images/ok16.png")); - _acceptClasspathButton.setName("acceptClasspathButton"); - _acceptClasspathButton.setText(Messages.getString("accept")); - jpanel1.add(_acceptClasspathButton,cc.xy(8,13)); - - _removeClasspathButton.setActionCommand("Remove"); - _removeClasspathButton.setIcon(loadImage("images/cancel16.png")); - _removeClasspathButton.setName("removeClasspathButton"); - _removeClasspathButton.setText(Messages.getString("remove")); - jpanel1.add(_removeClasspathButton,cc.xy(10,13)); - - _importClasspathButton.setIcon(loadImage("images/open16.png")); - _importClasspathButton.setName("importClasspathButton"); - _importClasspathButton.setToolTipText(Messages.getString("importClassPath")); - jpanel1.add(_importClasspathButton,cc.xy(12,4)); - - _classpathUpButton.setIcon(loadImage("images/up16.png")); - _classpathUpButton.setName("classpathUpButton"); - jpanel1.add(_classpathUpButton,cc.xy(12,6)); - - _classpathDownButton.setIcon(loadImage("images/down16.png")); - _classpathDownButton.setName("classpathDownButton"); - jpanel1.add(_classpathDownButton,cc.xy(12,8)); - - _classpathCheck.setActionCommand("Custom classpath"); - _classpathCheck.setName("classpathCheck"); - _classpathCheck.setText(Messages.getString("customClassPath")); - jpanel1.add(_classpathCheck,cc.xy(4,2)); - - _newClasspathButton.setActionCommand("New"); - _newClasspathButton.setIcon(loadImage("images/new16.png")); - _newClasspathButton.setName("newClasspathButton"); - _newClasspathButton.setText(Messages.getString("new")); - jpanel1.add(_newClasspathButton,cc.xy(6,13)); - - addFillComponents(jpanel1,new int[]{ 1,2,3,4,5,6,7,8,9,10,11,12,13 },new int[]{ 1,2,3,4,5,6,7,8,9,10,11,12,13,14 }); - return jpanel1; - } - - /** - * Initializer - */ - protected void initializePanel() - { - setLayout(new BorderLayout()); - add(createPanel(), BorderLayout.CENTER); - } - - -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/ClassPathForm.jfrm b/build/windows/launcher/launch4j/src/net/sf/launch4j/form/ClassPathForm.jfrm deleted file mode 100755 index 764329d2b82..00000000000 Binary files a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/ClassPathForm.jfrm and /dev/null differ diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/ConfigForm.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/form/ConfigForm.java deleted file mode 100755 index b3c6fffed31..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/ConfigForm.java +++ /dev/null @@ -1,132 +0,0 @@ -package net.sf.launch4j.form; - -import com.jeta.forms.components.separator.TitledSeparator; -import com.jgoodies.forms.layout.CellConstraints; -import com.jgoodies.forms.layout.FormLayout; -import java.awt.BorderLayout; -import java.awt.Container; -import java.awt.Dimension; -import javax.swing.Box; -import javax.swing.ImageIcon; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTabbedPane; -import javax.swing.JTextArea; - -public abstract class ConfigForm extends JPanel -{ - protected final JTextArea _logTextArea = new JTextArea(); - protected final TitledSeparator _logSeparator = new TitledSeparator(); - protected final JTabbedPane _tab = new JTabbedPane(); - - /** - * Default constructor - */ - public ConfigForm() - { - initializePanel(); - } - - /** - * Adds fill components to empty cells in the first row and first column of the grid. - * This ensures that the grid spacing will be the same as shown in the designer. - * @param cols an array of column indices in the first row where fill components should be added. - * @param rows an array of row indices in the first column where fill components should be added. - */ - void addFillComponents( Container panel, int[] cols, int[] rows ) - { - Dimension filler = new Dimension(10,10); - - boolean filled_cell_11 = false; - CellConstraints cc = new CellConstraints(); - if ( cols.length > 0 && rows.length > 0 ) - { - if ( cols[0] == 1 && rows[0] == 1 ) - { - /** add a rigid area */ - panel.add( Box.createRigidArea( filler ), cc.xy(1,1) ); - filled_cell_11 = true; - } - } - - for( int index = 0; index < cols.length; index++ ) - { - if ( cols[index] == 1 && filled_cell_11 ) - { - continue; - } - panel.add( Box.createRigidArea( filler ), cc.xy(cols[index],1) ); - } - - for( int index = 0; index < rows.length; index++ ) - { - if ( rows[index] == 1 && filled_cell_11 ) - { - continue; - } - panel.add( Box.createRigidArea( filler ), cc.xy(1,rows[index]) ); - } - - } - - /** - * Helper method to load an image file from the CLASSPATH - * @param imageName the package and name of the file to load relative to the CLASSPATH - * @return an ImageIcon instance with the specified image file - * @throws IllegalArgumentException if the image resource cannot be loaded. - */ - public ImageIcon loadImage( String imageName ) - { - try - { - ClassLoader classloader = getClass().getClassLoader(); - java.net.URL url = classloader.getResource( imageName ); - if ( url != null ) - { - ImageIcon icon = new ImageIcon( url ); - return icon; - } - } - catch( Exception e ) - { - e.printStackTrace(); - } - throw new IllegalArgumentException( "Unable to load image: " + imageName ); - } - - public JPanel createPanel() - { - JPanel jpanel1 = new JPanel(); - FormLayout formlayout1 = new FormLayout("FILL:7DLU:NONE,FILL:DEFAULT:GROW(1.0),FILL:7DLU:NONE","CENTER:3DLU:NONE,FILL:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,FILL:DEFAULT:GROW(1.0),CENTER:9DLU:NONE"); - CellConstraints cc = new CellConstraints(); - jpanel1.setLayout(formlayout1); - - _logTextArea.setName("logTextArea"); - JScrollPane jscrollpane1 = new JScrollPane(); - jscrollpane1.setViewportView(_logTextArea); - jscrollpane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); - jscrollpane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - jpanel1.add(jscrollpane1,cc.xy(2,6)); - - _logSeparator.setName("logSeparator"); - _logSeparator.setText(Messages.getString("log")); - jpanel1.add(_logSeparator,cc.xy(2,4)); - - _tab.setName("tab"); - jpanel1.add(_tab,cc.xywh(1,2,3,1)); - - addFillComponents(jpanel1,new int[]{ 1,2,3 },new int[]{ 1,3,4,5,6,7 }); - return jpanel1; - } - - /** - * Initializer - */ - protected void initializePanel() - { - setLayout(new BorderLayout()); - add(createPanel(), BorderLayout.CENTER); - } - - -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/ConfigForm.jfrm b/build/windows/launcher/launch4j/src/net/sf/launch4j/form/ConfigForm.jfrm deleted file mode 100755 index 2c6721e1409..00000000000 Binary files a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/ConfigForm.jfrm and /dev/null differ diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/EnvironmentVarsForm.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/form/EnvironmentVarsForm.java deleted file mode 100755 index f2b79e6e791..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/EnvironmentVarsForm.java +++ /dev/null @@ -1,127 +0,0 @@ -package net.sf.launch4j.form; - -import com.jgoodies.forms.layout.CellConstraints; -import com.jgoodies.forms.layout.FormLayout; -import java.awt.BorderLayout; -import java.awt.Container; -import java.awt.Dimension; -import javax.swing.Box; -import javax.swing.ImageIcon; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; - -public abstract class EnvironmentVarsForm extends JPanel -{ - protected final JTextArea _envVarsTextArea = new JTextArea(); - protected final JLabel _envVarsLabel = new JLabel(); - - /** - * Default constructor - */ - public EnvironmentVarsForm() - { - initializePanel(); - } - - /** - * Adds fill components to empty cells in the first row and first column of the grid. - * This ensures that the grid spacing will be the same as shown in the designer. - * @param cols an array of column indices in the first row where fill components should be added. - * @param rows an array of row indices in the first column where fill components should be added. - */ - void addFillComponents( Container panel, int[] cols, int[] rows ) - { - Dimension filler = new Dimension(10,10); - - boolean filled_cell_11 = false; - CellConstraints cc = new CellConstraints(); - if ( cols.length > 0 && rows.length > 0 ) - { - if ( cols[0] == 1 && rows[0] == 1 ) - { - /** add a rigid area */ - panel.add( Box.createRigidArea( filler ), cc.xy(1,1) ); - filled_cell_11 = true; - } - } - - for( int index = 0; index < cols.length; index++ ) - { - if ( cols[index] == 1 && filled_cell_11 ) - { - continue; - } - panel.add( Box.createRigidArea( filler ), cc.xy(cols[index],1) ); - } - - for( int index = 0; index < rows.length; index++ ) - { - if ( rows[index] == 1 && filled_cell_11 ) - { - continue; - } - panel.add( Box.createRigidArea( filler ), cc.xy(1,rows[index]) ); - } - - } - - /** - * Helper method to load an image file from the CLASSPATH - * @param imageName the package and name of the file to load relative to the CLASSPATH - * @return an ImageIcon instance with the specified image file - * @throws IllegalArgumentException if the image resource cannot be loaded. - */ - public ImageIcon loadImage( String imageName ) - { - try - { - ClassLoader classloader = getClass().getClassLoader(); - java.net.URL url = classloader.getResource( imageName ); - if ( url != null ) - { - ImageIcon icon = new ImageIcon( url ); - return icon; - } - } - catch( Exception e ) - { - e.printStackTrace(); - } - throw new IllegalArgumentException( "Unable to load image: " + imageName ); - } - - public JPanel createPanel() - { - JPanel jpanel1 = new JPanel(); - FormLayout formlayout1 = new FormLayout("FILL:7DLU:NONE,RIGHT:MAX(65DLU;DEFAULT):NONE,FILL:3DLU:NONE,FILL:DEFAULT:GROW(1.0),FILL:7DLU:NONE","CENTER:9DLU:NONE,FILL:DEFAULT:GROW(1.0),CENTER:9DLU:NONE"); - CellConstraints cc = new CellConstraints(); - jpanel1.setLayout(formlayout1); - - _envVarsTextArea.setName("envVarsTextArea"); - JScrollPane jscrollpane1 = new JScrollPane(); - jscrollpane1.setViewportView(_envVarsTextArea); - jscrollpane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); - jscrollpane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - jpanel1.add(jscrollpane1,cc.xy(4,2)); - - _envVarsLabel.setName("envVarsLabel"); - _envVarsLabel.setText(Messages.getString("setVariables")); - jpanel1.add(_envVarsLabel,new CellConstraints(2,2,1,1,CellConstraints.DEFAULT,CellConstraints.TOP)); - - addFillComponents(jpanel1,new int[]{ 1,2,3,4,5 },new int[]{ 1,2,3 }); - return jpanel1; - } - - /** - * Initializer - */ - protected void initializePanel() - { - setLayout(new BorderLayout()); - add(createPanel(), BorderLayout.CENTER); - } - - -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/EnvironmentVarsForm.jfrm b/build/windows/launcher/launch4j/src/net/sf/launch4j/form/EnvironmentVarsForm.jfrm deleted file mode 100755 index 6e89ec4d19a..00000000000 Binary files a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/EnvironmentVarsForm.jfrm and /dev/null differ diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/HeaderForm.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/form/HeaderForm.java deleted file mode 100755 index 91c40024ab9..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/HeaderForm.java +++ /dev/null @@ -1,171 +0,0 @@ -package net.sf.launch4j.form; - -import com.jeta.forms.components.separator.TitledSeparator; -import com.jgoodies.forms.layout.CellConstraints; -import com.jgoodies.forms.layout.FormLayout; -import java.awt.BorderLayout; -import java.awt.Container; -import java.awt.Dimension; -import javax.swing.Box; -import javax.swing.ButtonGroup; -import javax.swing.ImageIcon; -import javax.swing.JCheckBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JRadioButton; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; - -public abstract class HeaderForm extends JPanel -{ - protected final JLabel _headerTypeLabel = new JLabel(); - protected final JRadioButton _guiHeaderRadio = new JRadioButton(); - protected final ButtonGroup _headerButtonGroup = new ButtonGroup(); - protected final JRadioButton _consoleHeaderRadio = new JRadioButton(); - protected final JTextArea _headerObjectsTextArea = new JTextArea(); - protected final JTextArea _libsTextArea = new JTextArea(); - protected final JCheckBox _headerObjectsCheck = new JCheckBox(); - protected final JCheckBox _libsCheck = new JCheckBox(); - protected final TitledSeparator _linkerOptionsSeparator = new TitledSeparator(); - - /** - * Default constructor - */ - public HeaderForm() - { - initializePanel(); - } - - /** - * Adds fill components to empty cells in the first row and first column of the grid. - * This ensures that the grid spacing will be the same as shown in the designer. - * @param cols an array of column indices in the first row where fill components should be added. - * @param rows an array of row indices in the first column where fill components should be added. - */ - void addFillComponents( Container panel, int[] cols, int[] rows ) - { - Dimension filler = new Dimension(10,10); - - boolean filled_cell_11 = false; - CellConstraints cc = new CellConstraints(); - if ( cols.length > 0 && rows.length > 0 ) - { - if ( cols[0] == 1 && rows[0] == 1 ) - { - /** add a rigid area */ - panel.add( Box.createRigidArea( filler ), cc.xy(1,1) ); - filled_cell_11 = true; - } - } - - for( int index = 0; index < cols.length; index++ ) - { - if ( cols[index] == 1 && filled_cell_11 ) - { - continue; - } - panel.add( Box.createRigidArea( filler ), cc.xy(cols[index],1) ); - } - - for( int index = 0; index < rows.length; index++ ) - { - if ( rows[index] == 1 && filled_cell_11 ) - { - continue; - } - panel.add( Box.createRigidArea( filler ), cc.xy(1,rows[index]) ); - } - - } - - /** - * Helper method to load an image file from the CLASSPATH - * @param imageName the package and name of the file to load relative to the CLASSPATH - * @return an ImageIcon instance with the specified image file - * @throws IllegalArgumentException if the image resource cannot be loaded. - */ - public ImageIcon loadImage( String imageName ) - { - try - { - ClassLoader classloader = getClass().getClassLoader(); - java.net.URL url = classloader.getResource( imageName ); - if ( url != null ) - { - ImageIcon icon = new ImageIcon( url ); - return icon; - } - } - catch( Exception e ) - { - e.printStackTrace(); - } - throw new IllegalArgumentException( "Unable to load image: " + imageName ); - } - - public JPanel createPanel() - { - JPanel jpanel1 = new JPanel(); - FormLayout formlayout1 = new FormLayout("FILL:7DLU:NONE,RIGHT:MAX(65DLU;DEFAULT):NONE,FILL:3DLU:NONE,FILL:DEFAULT:NONE,FILL:7DLU:NONE,FILL:DEFAULT:NONE,FILL:DEFAULT:GROW(1.0),FILL:7DLU:NONE","CENTER:9DLU:NONE,CENTER:DEFAULT:NONE,CENTER:9DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,FILL:DEFAULT:GROW(0.2),CENTER:3DLU:NONE,FILL:DEFAULT:GROW(1.0),CENTER:9DLU:NONE"); - CellConstraints cc = new CellConstraints(); - jpanel1.setLayout(formlayout1); - - _headerTypeLabel.setName("headerTypeLabel"); - _headerTypeLabel.setText(Messages.getString("headerType")); - jpanel1.add(_headerTypeLabel,cc.xy(2,2)); - - _guiHeaderRadio.setActionCommand("GUI"); - _guiHeaderRadio.setName("guiHeaderRadio"); - _guiHeaderRadio.setText(Messages.getString("gui")); - _headerButtonGroup.add(_guiHeaderRadio); - jpanel1.add(_guiHeaderRadio,cc.xy(4,2)); - - _consoleHeaderRadio.setActionCommand("Console"); - _consoleHeaderRadio.setName("consoleHeaderRadio"); - _consoleHeaderRadio.setText(Messages.getString("console")); - _headerButtonGroup.add(_consoleHeaderRadio); - jpanel1.add(_consoleHeaderRadio,cc.xy(6,2)); - - _headerObjectsTextArea.setName("headerObjectsTextArea"); - JScrollPane jscrollpane1 = new JScrollPane(); - jscrollpane1.setViewportView(_headerObjectsTextArea); - jscrollpane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); - jscrollpane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - jpanel1.add(jscrollpane1,cc.xywh(4,6,4,1)); - - _libsTextArea.setName("libsTextArea"); - JScrollPane jscrollpane2 = new JScrollPane(); - jscrollpane2.setViewportView(_libsTextArea); - jscrollpane2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); - jscrollpane2.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - jpanel1.add(jscrollpane2,cc.xywh(4,8,4,1)); - - _headerObjectsCheck.setActionCommand("Object files"); - _headerObjectsCheck.setName("headerObjectsCheck"); - _headerObjectsCheck.setText(Messages.getString("objectFiles")); - jpanel1.add(_headerObjectsCheck,new CellConstraints(2,6,1,1,CellConstraints.DEFAULT,CellConstraints.TOP)); - - _libsCheck.setActionCommand("w32api"); - _libsCheck.setName("libsCheck"); - _libsCheck.setText(Messages.getString("libs")); - jpanel1.add(_libsCheck,new CellConstraints(2,8,1,1,CellConstraints.DEFAULT,CellConstraints.TOP)); - - _linkerOptionsSeparator.setName("linkerOptionsSeparator"); - _linkerOptionsSeparator.setText(Messages.getString("linkerOptions")); - jpanel1.add(_linkerOptionsSeparator,cc.xywh(2,4,6,1)); - - addFillComponents(jpanel1,new int[]{ 1,2,3,4,5,6,7,8 },new int[]{ 1,2,3,4,5,6,7,8,9 }); - return jpanel1; - } - - /** - * Initializer - */ - protected void initializePanel() - { - setLayout(new BorderLayout()); - add(createPanel(), BorderLayout.CENTER); - } - - -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/HeaderForm.jfrm b/build/windows/launcher/launch4j/src/net/sf/launch4j/form/HeaderForm.jfrm deleted file mode 100755 index a7cbed1445d..00000000000 Binary files a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/HeaderForm.jfrm and /dev/null differ diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/JreForm.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/form/JreForm.java deleted file mode 100755 index ed16c50b6a4..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/JreForm.java +++ /dev/null @@ -1,266 +0,0 @@ -package net.sf.launch4j.form; - -import com.jgoodies.forms.layout.CellConstraints; -import com.jgoodies.forms.layout.FormLayout; -import java.awt.BorderLayout; -import java.awt.Container; -import java.awt.Dimension; -import javax.swing.Box; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; -import javax.swing.JTextField; - -public abstract class JreForm extends JPanel -{ - protected final JLabel _jrePathLabel = new JLabel(); - protected final JLabel _jreMinLabel = new JLabel(); - protected final JLabel _jreMaxLabel = new JLabel(); - protected final JLabel _jvmOptionsTextLabel = new JLabel(); - protected final JTextField _jrePathField = new JTextField(); - protected final JTextField _jreMinField = new JTextField(); - protected final JTextField _jreMaxField = new JTextField(); - protected final JTextArea _jvmOptionsTextArea = new JTextArea(); - protected final JLabel _initialHeapSizeLabel = new JLabel(); - protected final JLabel _maxHeapSizeLabel = new JLabel(); - protected final JTextField _initialHeapSizeField = new JTextField(); - protected final JTextField _maxHeapSizeField = new JTextField(); - protected final JComboBox _varCombo = new JComboBox(); - protected final JButton _propertyButton = new JButton(); - protected final JButton _optionButton = new JButton(); - protected final JButton _envPropertyButton = new JButton(); - protected final JButton _envOptionButton = new JButton(); - protected final JTextField _envVarField = new JTextField(); - protected final JTextField _maxHeapPercentField = new JTextField(); - protected final JTextField _initialHeapPercentField = new JTextField(); - protected final JComboBox _jdkPreferenceCombo = new JComboBox(); - - /** - * Default constructor - */ - public JreForm() - { - initializePanel(); - } - - /** - * Adds fill components to empty cells in the first row and first column of the grid. - * This ensures that the grid spacing will be the same as shown in the designer. - * @param cols an array of column indices in the first row where fill components should be added. - * @param rows an array of row indices in the first column where fill components should be added. - */ - void addFillComponents( Container panel, int[] cols, int[] rows ) - { - Dimension filler = new Dimension(10,10); - - boolean filled_cell_11 = false; - CellConstraints cc = new CellConstraints(); - if ( cols.length > 0 && rows.length > 0 ) - { - if ( cols[0] == 1 && rows[0] == 1 ) - { - /** add a rigid area */ - panel.add( Box.createRigidArea( filler ), cc.xy(1,1) ); - filled_cell_11 = true; - } - } - - for( int index = 0; index < cols.length; index++ ) - { - if ( cols[index] == 1 && filled_cell_11 ) - { - continue; - } - panel.add( Box.createRigidArea( filler ), cc.xy(cols[index],1) ); - } - - for( int index = 0; index < rows.length; index++ ) - { - if ( rows[index] == 1 && filled_cell_11 ) - { - continue; - } - panel.add( Box.createRigidArea( filler ), cc.xy(1,rows[index]) ); - } - - } - - /** - * Helper method to load an image file from the CLASSPATH - * @param imageName the package and name of the file to load relative to the CLASSPATH - * @return an ImageIcon instance with the specified image file - * @throws IllegalArgumentException if the image resource cannot be loaded. - */ - public ImageIcon loadImage( String imageName ) - { - try - { - ClassLoader classloader = getClass().getClassLoader(); - java.net.URL url = classloader.getResource( imageName ); - if ( url != null ) - { - ImageIcon icon = new ImageIcon( url ); - return icon; - } - } - catch( Exception e ) - { - e.printStackTrace(); - } - throw new IllegalArgumentException( "Unable to load image: " + imageName ); - } - - public JPanel createPanel() - { - JPanel jpanel1 = new JPanel(); - FormLayout formlayout1 = new FormLayout("FILL:7DLU:NONE,RIGHT:MAX(65DLU;DEFAULT):NONE,FILL:3DLU:NONE,FILL:60DLU:NONE,FILL:3DLU:NONE,FILL:DEFAULT:NONE,FILL:7DLU:NONE,FILL:60DLU:NONE,FILL:3DLU:NONE,FILL:DEFAULT:GROW(1.0),FILL:7DLU:NONE","CENTER:9DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,FILL:50DLU:GROW(1.0),CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:9DLU:NONE"); - CellConstraints cc = new CellConstraints(); - jpanel1.setLayout(formlayout1); - - _jrePathLabel.setName("jrePathLabel"); - _jrePathLabel.setText(Messages.getString("jrePath")); - jpanel1.add(_jrePathLabel,cc.xy(2,2)); - - _jreMinLabel.setName("jreMinLabel"); - _jreMinLabel.setText(Messages.getString("jreMin")); - jpanel1.add(_jreMinLabel,cc.xy(2,4)); - - _jreMaxLabel.setName("jreMaxLabel"); - _jreMaxLabel.setText(Messages.getString("jreMax")); - jpanel1.add(_jreMaxLabel,cc.xy(2,6)); - - _jvmOptionsTextLabel.setName("jvmOptionsTextLabel"); - _jvmOptionsTextLabel.setText(Messages.getString("jvmOptions")); - jpanel1.add(_jvmOptionsTextLabel,new CellConstraints(2,12,1,1,CellConstraints.DEFAULT,CellConstraints.TOP)); - - _jrePathField.setName("jrePathField"); - _jrePathField.setToolTipText(Messages.getString("jrePathTip")); - jpanel1.add(_jrePathField,cc.xywh(4,2,7,1)); - - _jreMinField.setName("jreMinField"); - jpanel1.add(_jreMinField,cc.xy(4,4)); - - _jreMaxField.setName("jreMaxField"); - jpanel1.add(_jreMaxField,cc.xy(4,6)); - - _jvmOptionsTextArea.setName("jvmOptionsTextArea"); - _jvmOptionsTextArea.setToolTipText(Messages.getString("jvmOptionsTip")); - JScrollPane jscrollpane1 = new JScrollPane(); - jscrollpane1.setViewportView(_jvmOptionsTextArea); - jscrollpane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); - jscrollpane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - jpanel1.add(jscrollpane1,cc.xywh(4,12,7,1)); - - _initialHeapSizeLabel.setName("initialHeapSizeLabel"); - _initialHeapSizeLabel.setText(Messages.getString("initialHeapSize")); - jpanel1.add(_initialHeapSizeLabel,cc.xy(2,8)); - - _maxHeapSizeLabel.setName("maxHeapSizeLabel"); - _maxHeapSizeLabel.setText(Messages.getString("maxHeapSize")); - jpanel1.add(_maxHeapSizeLabel,cc.xy(2,10)); - - JLabel jlabel1 = new JLabel(); - jlabel1.setText("MB"); - jpanel1.add(jlabel1,cc.xy(6,8)); - - JLabel jlabel2 = new JLabel(); - jlabel2.setText("MB"); - jpanel1.add(jlabel2,cc.xy(6,10)); - - _initialHeapSizeField.setName("initialHeapSizeField"); - jpanel1.add(_initialHeapSizeField,cc.xy(4,8)); - - _maxHeapSizeField.setName("maxHeapSizeField"); - jpanel1.add(_maxHeapSizeField,cc.xy(4,10)); - - jpanel1.add(createPanel1(),cc.xywh(2,14,9,1)); - _maxHeapPercentField.setName("maxHeapPercentField"); - jpanel1.add(_maxHeapPercentField,cc.xy(8,10)); - - _initialHeapPercentField.setName("initialHeapPercentField"); - jpanel1.add(_initialHeapPercentField,cc.xy(8,8)); - - _jdkPreferenceCombo.setName("jdkPreferenceCombo"); - jpanel1.add(_jdkPreferenceCombo,cc.xywh(8,4,3,1)); - - JLabel jlabel3 = new JLabel(); - jlabel3.setText(Messages.getString("freeMemory")); - jpanel1.add(jlabel3,cc.xy(10,8)); - - JLabel jlabel4 = new JLabel(); - jlabel4.setText(Messages.getString("freeMemory")); - jpanel1.add(jlabel4,cc.xy(10,10)); - - addFillComponents(jpanel1,new int[]{ 1,2,3,4,5,6,7,8,9,10,11 },new int[]{ 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 }); - return jpanel1; - } - - public JPanel createPanel1() - { - JPanel jpanel1 = new JPanel(); - FormLayout formlayout1 = new FormLayout("RIGHT:MAX(65DLU;DEFAULT):NONE,FILL:3DLU:NONE,FILL:DEFAULT:GROW(1.0),FILL:3DLU:NONE,FILL:DEFAULT:NONE,FILL:3DLU:NONE,FILL:DEFAULT:NONE","CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE"); - CellConstraints cc = new CellConstraints(); - jpanel1.setLayout(formlayout1); - - _varCombo.setName("varCombo"); - jpanel1.add(_varCombo,cc.xy(3,1)); - - _propertyButton.setActionCommand("Add"); - _propertyButton.setIcon(loadImage("images/edit_add16.png")); - _propertyButton.setName("propertyButton"); - _propertyButton.setText(Messages.getString("property")); - _propertyButton.setToolTipText(Messages.getString("propertyTip")); - jpanel1.add(_propertyButton,cc.xy(5,1)); - - _optionButton.setActionCommand("Add"); - _optionButton.setIcon(loadImage("images/edit_add16.png")); - _optionButton.setName("optionButton"); - _optionButton.setText(Messages.getString("option")); - _optionButton.setToolTipText(Messages.getString("optionTip")); - jpanel1.add(_optionButton,cc.xy(7,1)); - - _envPropertyButton.setActionCommand("Add"); - _envPropertyButton.setIcon(loadImage("images/edit_add16.png")); - _envPropertyButton.setName("envPropertyButton"); - _envPropertyButton.setText(Messages.getString("property")); - _envPropertyButton.setToolTipText(Messages.getString("propertyTip")); - jpanel1.add(_envPropertyButton,cc.xy(5,3)); - - JLabel jlabel1 = new JLabel(); - jlabel1.setText(Messages.getString("varsAndRegistry")); - jpanel1.add(jlabel1,cc.xy(1,1)); - - JLabel jlabel2 = new JLabel(); - jlabel2.setIcon(loadImage("images/asterix.gif")); - jlabel2.setText(Messages.getString("envVar")); - jpanel1.add(jlabel2,cc.xy(1,3)); - - _envOptionButton.setActionCommand("Add"); - _envOptionButton.setIcon(loadImage("images/edit_add16.png")); - _envOptionButton.setName("envOptionButton"); - _envOptionButton.setText(Messages.getString("option")); - _envOptionButton.setToolTipText(Messages.getString("optionTip")); - jpanel1.add(_envOptionButton,cc.xy(7,3)); - - _envVarField.setName("envVarField"); - jpanel1.add(_envVarField,cc.xy(3,3)); - - addFillComponents(jpanel1,new int[]{ 2,4,6 },new int[]{ 2 }); - return jpanel1; - } - - /** - * Initializer - */ - protected void initializePanel() - { - setLayout(new BorderLayout()); - add(createPanel(), BorderLayout.CENTER); - } - - -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/JreForm.jfrm b/build/windows/launcher/launch4j/src/net/sf/launch4j/form/JreForm.jfrm deleted file mode 100755 index 1e61237e0f3..00000000000 Binary files a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/JreForm.jfrm and /dev/null differ diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/Messages.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/form/Messages.java deleted file mode 100755 index aaf995f8019..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/Messages.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -package net.sf.launch4j.form; - -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -class Messages { - private static final String BUNDLE_NAME = "net.sf.launch4j.form.messages"; - - private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle - .getBundle(BUNDLE_NAME); - - private Messages() { - } - - public static String getString(String key) { - try { - return RESOURCE_BUNDLE.getString(key); - } catch (MissingResourceException e) { - return '!' + key + '!'; - } - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/MessagesForm.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/form/MessagesForm.java deleted file mode 100755 index f2e8723da75..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/MessagesForm.java +++ /dev/null @@ -1,183 +0,0 @@ -package net.sf.launch4j.form; - -import com.jgoodies.forms.layout.CellConstraints; -import com.jgoodies.forms.layout.FormLayout; -import java.awt.BorderLayout; -import java.awt.Container; -import java.awt.Dimension; -import javax.swing.Box; -import javax.swing.ImageIcon; -import javax.swing.JCheckBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; - -public abstract class MessagesForm extends JPanel -{ - protected final JTextArea _startupErrTextArea = new JTextArea(); - protected final JTextArea _bundledJreErrTextArea = new JTextArea(); - protected final JTextArea _jreVersionErrTextArea = new JTextArea(); - protected final JTextArea _launcherErrTextArea = new JTextArea(); - protected final JCheckBox _messagesCheck = new JCheckBox(); - protected final JTextArea _instanceAlreadyExistsMsgTextArea = new JTextArea(); - - /** - * Default constructor - */ - public MessagesForm() - { - initializePanel(); - } - - /** - * Adds fill components to empty cells in the first row and first column of the grid. - * This ensures that the grid spacing will be the same as shown in the designer. - * @param cols an array of column indices in the first row where fill components should be added. - * @param rows an array of row indices in the first column where fill components should be added. - */ - void addFillComponents( Container panel, int[] cols, int[] rows ) - { - Dimension filler = new Dimension(10,10); - - boolean filled_cell_11 = false; - CellConstraints cc = new CellConstraints(); - if ( cols.length > 0 && rows.length > 0 ) - { - if ( cols[0] == 1 && rows[0] == 1 ) - { - /** add a rigid area */ - panel.add( Box.createRigidArea( filler ), cc.xy(1,1) ); - filled_cell_11 = true; - } - } - - for( int index = 0; index < cols.length; index++ ) - { - if ( cols[index] == 1 && filled_cell_11 ) - { - continue; - } - panel.add( Box.createRigidArea( filler ), cc.xy(cols[index],1) ); - } - - for( int index = 0; index < rows.length; index++ ) - { - if ( rows[index] == 1 && filled_cell_11 ) - { - continue; - } - panel.add( Box.createRigidArea( filler ), cc.xy(1,rows[index]) ); - } - - } - - /** - * Helper method to load an image file from the CLASSPATH - * @param imageName the package and name of the file to load relative to the CLASSPATH - * @return an ImageIcon instance with the specified image file - * @throws IllegalArgumentException if the image resource cannot be loaded. - */ - public ImageIcon loadImage( String imageName ) - { - try - { - ClassLoader classloader = getClass().getClassLoader(); - java.net.URL url = classloader.getResource( imageName ); - if ( url != null ) - { - ImageIcon icon = new ImageIcon( url ); - return icon; - } - } - catch( Exception e ) - { - e.printStackTrace(); - } - throw new IllegalArgumentException( "Unable to load image: " + imageName ); - } - - public JPanel createPanel() - { - JPanel jpanel1 = new JPanel(); - FormLayout formlayout1 = new FormLayout("FILL:7DLU:NONE,RIGHT:MAX(65DLU;DEFAULT):NONE,FILL:3DLU:NONE,FILL:DEFAULT:GROW(1.0),FILL:7DLU:NONE","CENTER:9DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,FILL:DEFAULT:GROW(1.0),CENTER:3DLU:NONE,FILL:DEFAULT:GROW(1.0),CENTER:3DLU:NONE,FILL:DEFAULT:GROW(1.0),CENTER:3DLU:NONE,FILL:DEFAULT:GROW(1.0),CENTER:3DLU:NONE,FILL:DEFAULT:GROW(1.0),CENTER:9DLU:NONE"); - CellConstraints cc = new CellConstraints(); - jpanel1.setLayout(formlayout1); - - _startupErrTextArea.setName("startupErrTextArea"); - JScrollPane jscrollpane1 = new JScrollPane(); - jscrollpane1.setViewportView(_startupErrTextArea); - jscrollpane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); - jscrollpane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - jpanel1.add(jscrollpane1,cc.xy(4,4)); - - _bundledJreErrTextArea.setName("bundledJreErrTextArea"); - JScrollPane jscrollpane2 = new JScrollPane(); - jscrollpane2.setViewportView(_bundledJreErrTextArea); - jscrollpane2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); - jscrollpane2.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - jpanel1.add(jscrollpane2,cc.xy(4,6)); - - _jreVersionErrTextArea.setName("jreVersionErrTextArea"); - _jreVersionErrTextArea.setToolTipText(Messages.getString("jreVersionErrTip")); - JScrollPane jscrollpane3 = new JScrollPane(); - jscrollpane3.setViewportView(_jreVersionErrTextArea); - jscrollpane3.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); - jscrollpane3.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - jpanel1.add(jscrollpane3,cc.xy(4,8)); - - _launcherErrTextArea.setName("launcherErrTextArea"); - JScrollPane jscrollpane4 = new JScrollPane(); - jscrollpane4.setViewportView(_launcherErrTextArea); - jscrollpane4.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); - jscrollpane4.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - jpanel1.add(jscrollpane4,cc.xy(4,10)); - - JLabel jlabel1 = new JLabel(); - jlabel1.setText(Messages.getString("startupErr")); - jpanel1.add(jlabel1,new CellConstraints(2,4,1,1,CellConstraints.DEFAULT,CellConstraints.TOP)); - - JLabel jlabel2 = new JLabel(); - jlabel2.setText(Messages.getString("bundledJreErr")); - jpanel1.add(jlabel2,new CellConstraints(2,6,1,1,CellConstraints.DEFAULT,CellConstraints.TOP)); - - JLabel jlabel3 = new JLabel(); - jlabel3.setText(Messages.getString("jreVersionErr")); - jpanel1.add(jlabel3,new CellConstraints(2,8,1,1,CellConstraints.DEFAULT,CellConstraints.TOP)); - - JLabel jlabel4 = new JLabel(); - jlabel4.setText(Messages.getString("launcherErr")); - jpanel1.add(jlabel4,new CellConstraints(2,10,1,1,CellConstraints.DEFAULT,CellConstraints.TOP)); - - _messagesCheck.setActionCommand("Add version information"); - _messagesCheck.setName("messagesCheck"); - _messagesCheck.setText(Messages.getString("addMessages")); - jpanel1.add(_messagesCheck,cc.xy(4,2)); - - JLabel jlabel5 = new JLabel(); - jlabel5.setText(Messages.getString("instanceAlreadyExistsMsg")); - jpanel1.add(jlabel5,new CellConstraints(2,12,1,1,CellConstraints.DEFAULT,CellConstraints.TOP)); - - _instanceAlreadyExistsMsgTextArea.setName("instanceAlreadyExistsMsgTextArea"); - _instanceAlreadyExistsMsgTextArea.setToolTipText(Messages.getString("instanceAlreadyExistsMsgTip")); - JScrollPane jscrollpane5 = new JScrollPane(); - jscrollpane5.setViewportView(_instanceAlreadyExistsMsgTextArea); - jscrollpane5.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); - jscrollpane5.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - jpanel1.add(jscrollpane5,cc.xy(4,12)); - - addFillComponents(jpanel1,new int[]{ 1,2,3,4,5 },new int[]{ 1,2,3,4,5,6,7,8,9,10,11,12,13 }); - return jpanel1; - } - - /** - * Initializer - */ - protected void initializePanel() - { - setLayout(new BorderLayout()); - add(createPanel(), BorderLayout.CENTER); - } - - -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/MessagesForm.jfrm b/build/windows/launcher/launch4j/src/net/sf/launch4j/form/MessagesForm.jfrm deleted file mode 100755 index e8044dfd7c0..00000000000 Binary files a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/MessagesForm.jfrm and /dev/null differ diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/SingleInstanceForm.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/form/SingleInstanceForm.java deleted file mode 100755 index 2bfe724a665..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/SingleInstanceForm.java +++ /dev/null @@ -1,141 +0,0 @@ -package net.sf.launch4j.form; - -import com.jgoodies.forms.layout.CellConstraints; -import com.jgoodies.forms.layout.FormLayout; -import java.awt.BorderLayout; -import java.awt.Container; -import java.awt.Dimension; -import javax.swing.Box; -import javax.swing.ImageIcon; -import javax.swing.JCheckBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextField; - -public abstract class SingleInstanceForm extends JPanel -{ - protected final JLabel _splashFileLabel = new JLabel(); - protected final JTextField _mutexNameField = new JTextField(); - protected final JCheckBox _singleInstanceCheck = new JCheckBox(); - protected final JTextField _windowTitleField = new JTextField(); - protected final JLabel _splashFileLabel1 = new JLabel(); - - /** - * Default constructor - */ - public SingleInstanceForm() - { - initializePanel(); - } - - /** - * Adds fill components to empty cells in the first row and first column of the grid. - * This ensures that the grid spacing will be the same as shown in the designer. - * @param cols an array of column indices in the first row where fill components should be added. - * @param rows an array of row indices in the first column where fill components should be added. - */ - void addFillComponents( Container panel, int[] cols, int[] rows ) - { - Dimension filler = new Dimension(10,10); - - boolean filled_cell_11 = false; - CellConstraints cc = new CellConstraints(); - if ( cols.length > 0 && rows.length > 0 ) - { - if ( cols[0] == 1 && rows[0] == 1 ) - { - /** add a rigid area */ - panel.add( Box.createRigidArea( filler ), cc.xy(1,1) ); - filled_cell_11 = true; - } - } - - for( int index = 0; index < cols.length; index++ ) - { - if ( cols[index] == 1 && filled_cell_11 ) - { - continue; - } - panel.add( Box.createRigidArea( filler ), cc.xy(cols[index],1) ); - } - - for( int index = 0; index < rows.length; index++ ) - { - if ( rows[index] == 1 && filled_cell_11 ) - { - continue; - } - panel.add( Box.createRigidArea( filler ), cc.xy(1,rows[index]) ); - } - - } - - /** - * Helper method to load an image file from the CLASSPATH - * @param imageName the package and name of the file to load relative to the CLASSPATH - * @return an ImageIcon instance with the specified image file - * @throws IllegalArgumentException if the image resource cannot be loaded. - */ - public ImageIcon loadImage( String imageName ) - { - try - { - ClassLoader classloader = getClass().getClassLoader(); - java.net.URL url = classloader.getResource( imageName ); - if ( url != null ) - { - ImageIcon icon = new ImageIcon( url ); - return icon; - } - } - catch( Exception e ) - { - e.printStackTrace(); - } - throw new IllegalArgumentException( "Unable to load image: " + imageName ); - } - - public JPanel createPanel() - { - JPanel jpanel1 = new JPanel(); - FormLayout formlayout1 = new FormLayout("FILL:7DLU:NONE,RIGHT:MAX(65DLU;DEFAULT):NONE,FILL:3DLU:NONE,FILL:60DLU:NONE,FILL:DEFAULT:GROW(1.0),FILL:7DLU:NONE","CENTER:9DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:9DLU:NONE"); - CellConstraints cc = new CellConstraints(); - jpanel1.setLayout(formlayout1); - - _splashFileLabel.setIcon(loadImage("images/asterix.gif")); - _splashFileLabel.setName("splashFileLabel"); - _splashFileLabel.setText(Messages.getString("mutexName")); - jpanel1.add(_splashFileLabel,cc.xy(2,4)); - - _mutexNameField.setName("mutexNameField"); - _mutexNameField.setToolTipText(Messages.getString("mutexNameTip")); - jpanel1.add(_mutexNameField,cc.xywh(4,4,2,1)); - - _singleInstanceCheck.setActionCommand("Enable splash screen"); - _singleInstanceCheck.setName("singleInstanceCheck"); - _singleInstanceCheck.setText(Messages.getString("enableSingleInstance")); - jpanel1.add(_singleInstanceCheck,cc.xywh(4,2,2,1)); - - _windowTitleField.setName("windowTitleField"); - _windowTitleField.setToolTipText(Messages.getString("windowTitleTip")); - jpanel1.add(_windowTitleField,cc.xywh(4,6,2,1)); - - _splashFileLabel1.setName("splashFileLabel"); - _splashFileLabel1.setText(Messages.getString("windowTitle")); - jpanel1.add(_splashFileLabel1,cc.xy(2,6)); - - addFillComponents(jpanel1,new int[]{ 1,2,3,4,5,6 },new int[]{ 1,2,3,4,5,6,7 }); - return jpanel1; - } - - /** - * Initializer - */ - protected void initializePanel() - { - setLayout(new BorderLayout()); - add(createPanel(), BorderLayout.CENTER); - } - - -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/SingleInstanceForm.jfrm b/build/windows/launcher/launch4j/src/net/sf/launch4j/form/SingleInstanceForm.jfrm deleted file mode 100755 index c9d7ce28daa..00000000000 Binary files a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/SingleInstanceForm.jfrm and /dev/null differ diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/SplashForm.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/form/SplashForm.java deleted file mode 100755 index 22a0ed8a3d0..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/SplashForm.java +++ /dev/null @@ -1,166 +0,0 @@ -package net.sf.launch4j.form; - -import com.jgoodies.forms.layout.CellConstraints; -import com.jgoodies.forms.layout.FormLayout; -import java.awt.BorderLayout; -import java.awt.Container; -import java.awt.Dimension; -import javax.swing.Box; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextField; - -public abstract class SplashForm extends JPanel -{ - protected final JLabel _splashFileLabel = new JLabel(); - protected final JLabel _waitForWindowLabel = new JLabel(); - protected final JLabel _timeoutLabel = new JLabel(); - protected final JCheckBox _timeoutErrCheck = new JCheckBox(); - protected final JTextField _splashFileField = new JTextField(); - protected final JTextField _timeoutField = new JTextField(); - protected final JButton _splashFileButton = new JButton(); - protected final JCheckBox _splashCheck = new JCheckBox(); - protected final JCheckBox _waitForWindowCheck = new JCheckBox(); - - /** - * Default constructor - */ - public SplashForm() - { - initializePanel(); - } - - /** - * Adds fill components to empty cells in the first row and first column of the grid. - * This ensures that the grid spacing will be the same as shown in the designer. - * @param cols an array of column indices in the first row where fill components should be added. - * @param rows an array of row indices in the first column where fill components should be added. - */ - void addFillComponents( Container panel, int[] cols, int[] rows ) - { - Dimension filler = new Dimension(10,10); - - boolean filled_cell_11 = false; - CellConstraints cc = new CellConstraints(); - if ( cols.length > 0 && rows.length > 0 ) - { - if ( cols[0] == 1 && rows[0] == 1 ) - { - /** add a rigid area */ - panel.add( Box.createRigidArea( filler ), cc.xy(1,1) ); - filled_cell_11 = true; - } - } - - for( int index = 0; index < cols.length; index++ ) - { - if ( cols[index] == 1 && filled_cell_11 ) - { - continue; - } - panel.add( Box.createRigidArea( filler ), cc.xy(cols[index],1) ); - } - - for( int index = 0; index < rows.length; index++ ) - { - if ( rows[index] == 1 && filled_cell_11 ) - { - continue; - } - panel.add( Box.createRigidArea( filler ), cc.xy(1,rows[index]) ); - } - - } - - /** - * Helper method to load an image file from the CLASSPATH - * @param imageName the package and name of the file to load relative to the CLASSPATH - * @return an ImageIcon instance with the specified image file - * @throws IllegalArgumentException if the image resource cannot be loaded. - */ - public ImageIcon loadImage( String imageName ) - { - try - { - ClassLoader classloader = getClass().getClassLoader(); - java.net.URL url = classloader.getResource( imageName ); - if ( url != null ) - { - ImageIcon icon = new ImageIcon( url ); - return icon; - } - } - catch( Exception e ) - { - e.printStackTrace(); - } - throw new IllegalArgumentException( "Unable to load image: " + imageName ); - } - - public JPanel createPanel() - { - JPanel jpanel1 = new JPanel(); - FormLayout formlayout1 = new FormLayout("FILL:7DLU:NONE,RIGHT:MAX(65DLU;DEFAULT):NONE,FILL:3DLU:NONE,FILL:60DLU:NONE,FILL:DEFAULT:GROW(1.0),FILL:3DLU:NONE,FILL:26PX:NONE,FILL:7DLU:NONE","CENTER:9DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:9DLU:NONE"); - CellConstraints cc = new CellConstraints(); - jpanel1.setLayout(formlayout1); - - _splashFileLabel.setIcon(loadImage("images/asterix.gif")); - _splashFileLabel.setName("splashFileLabel"); - _splashFileLabel.setText(Messages.getString("splashFile")); - jpanel1.add(_splashFileLabel,cc.xy(2,4)); - - _waitForWindowLabel.setName("waitForWindowLabel"); - _waitForWindowLabel.setText(Messages.getString("waitForWindow")); - jpanel1.add(_waitForWindowLabel,cc.xy(2,6)); - - _timeoutLabel.setIcon(loadImage("images/asterix.gif")); - _timeoutLabel.setName("timeoutLabel"); - _timeoutLabel.setText(Messages.getString("timeout")); - jpanel1.add(_timeoutLabel,cc.xy(2,8)); - - _timeoutErrCheck.setActionCommand("Signal error on timeout"); - _timeoutErrCheck.setName("timeoutErrCheck"); - _timeoutErrCheck.setText(Messages.getString("timeoutErr")); - _timeoutErrCheck.setToolTipText(Messages.getString("timeoutErrTip")); - jpanel1.add(_timeoutErrCheck,cc.xywh(4,10,2,1)); - - _splashFileField.setName("splashFileField"); - _splashFileField.setToolTipText(Messages.getString("splashFileTip")); - jpanel1.add(_splashFileField,cc.xywh(4,4,2,1)); - - _timeoutField.setName("timeoutField"); - _timeoutField.setToolTipText(Messages.getString("timeoutTip")); - jpanel1.add(_timeoutField,cc.xy(4,8)); - - _splashFileButton.setIcon(loadImage("images/open16.png")); - _splashFileButton.setName("splashFileButton"); - jpanel1.add(_splashFileButton,cc.xy(7,4)); - - _splashCheck.setActionCommand("Enable splash screen"); - _splashCheck.setName("splashCheck"); - _splashCheck.setText(Messages.getString("enableSplash")); - jpanel1.add(_splashCheck,cc.xywh(4,2,2,1)); - - _waitForWindowCheck.setActionCommand("Close splash screen when an application window appears"); - _waitForWindowCheck.setName("waitForWindowCheck"); - _waitForWindowCheck.setText(Messages.getString("waitForWindowText")); - jpanel1.add(_waitForWindowCheck,cc.xywh(4,6,2,1)); - - addFillComponents(jpanel1,new int[]{ 1,2,3,4,5,6,7,8 },new int[]{ 1,2,3,4,5,6,7,8,9,10,11 }); - return jpanel1; - } - - /** - * Initializer - */ - protected void initializePanel() - { - setLayout(new BorderLayout()); - add(createPanel(), BorderLayout.CENTER); - } - - -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/SplashForm.jfrm b/build/windows/launcher/launch4j/src/net/sf/launch4j/form/SplashForm.jfrm deleted file mode 100755 index 114f0e31de9..00000000000 Binary files a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/SplashForm.jfrm and /dev/null differ diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/VersionInfoForm.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/form/VersionInfoForm.java deleted file mode 100755 index 5a4d9440c60..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/VersionInfoForm.java +++ /dev/null @@ -1,232 +0,0 @@ -package net.sf.launch4j.form; - -import com.jeta.forms.components.separator.TitledSeparator; -import com.jgoodies.forms.layout.CellConstraints; -import com.jgoodies.forms.layout.FormLayout; -import java.awt.BorderLayout; -import java.awt.Container; -import java.awt.Dimension; -import javax.swing.Box; -import javax.swing.ImageIcon; -import javax.swing.JCheckBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextField; - -public abstract class VersionInfoForm extends JPanel -{ - protected final JCheckBox _versionInfoCheck = new JCheckBox(); - protected final JLabel _fileVersionLabel = new JLabel(); - protected final JTextField _fileVersionField = new JTextField(); - protected final TitledSeparator _addVersionInfoSeparator = new TitledSeparator(); - protected final JLabel _productVersionLabel = new JLabel(); - protected final JTextField _productVersionField = new JTextField(); - protected final JLabel _fileDescriptionLabel = new JLabel(); - protected final JTextField _fileDescriptionField = new JTextField(); - protected final JLabel _copyrightLabel = new JLabel(); - protected final JTextField _copyrightField = new JTextField(); - protected final JLabel _txtFileVersionLabel = new JLabel(); - protected final JTextField _txtFileVersionField = new JTextField(); - protected final JLabel _txtProductVersionLabel = new JLabel(); - protected final JTextField _txtProductVersionField = new JTextField(); - protected final JLabel _productNameLabel = new JLabel(); - protected final JTextField _productNameField = new JTextField(); - protected final JLabel _originalFilenameLabel = new JLabel(); - protected final JTextField _originalFilenameField = new JTextField(); - protected final JLabel _internalNameLabel = new JLabel(); - protected final JTextField _internalNameField = new JTextField(); - protected final JLabel _companyNameLabel = new JLabel(); - protected final JTextField _companyNameField = new JTextField(); - - /** - * Default constructor - */ - public VersionInfoForm() - { - initializePanel(); - } - - /** - * Adds fill components to empty cells in the first row and first column of the grid. - * This ensures that the grid spacing will be the same as shown in the designer. - * @param cols an array of column indices in the first row where fill components should be added. - * @param rows an array of row indices in the first column where fill components should be added. - */ - void addFillComponents( Container panel, int[] cols, int[] rows ) - { - Dimension filler = new Dimension(10,10); - - boolean filled_cell_11 = false; - CellConstraints cc = new CellConstraints(); - if ( cols.length > 0 && rows.length > 0 ) - { - if ( cols[0] == 1 && rows[0] == 1 ) - { - /** add a rigid area */ - panel.add( Box.createRigidArea( filler ), cc.xy(1,1) ); - filled_cell_11 = true; - } - } - - for( int index = 0; index < cols.length; index++ ) - { - if ( cols[index] == 1 && filled_cell_11 ) - { - continue; - } - panel.add( Box.createRigidArea( filler ), cc.xy(cols[index],1) ); - } - - for( int index = 0; index < rows.length; index++ ) - { - if ( rows[index] == 1 && filled_cell_11 ) - { - continue; - } - panel.add( Box.createRigidArea( filler ), cc.xy(1,rows[index]) ); - } - - } - - /** - * Helper method to load an image file from the CLASSPATH - * @param imageName the package and name of the file to load relative to the CLASSPATH - * @return an ImageIcon instance with the specified image file - * @throws IllegalArgumentException if the image resource cannot be loaded. - */ - public ImageIcon loadImage( String imageName ) - { - try - { - ClassLoader classloader = getClass().getClassLoader(); - java.net.URL url = classloader.getResource( imageName ); - if ( url != null ) - { - ImageIcon icon = new ImageIcon( url ); - return icon; - } - } - catch( Exception e ) - { - e.printStackTrace(); - } - throw new IllegalArgumentException( "Unable to load image: " + imageName ); - } - - public JPanel createPanel() - { - JPanel jpanel1 = new JPanel(); - FormLayout formlayout1 = new FormLayout("FILL:7DLU:NONE,RIGHT:MAX(65DLU;DEFAULT):NONE,FILL:3DLU:NONE,FILL:60DLU:NONE,FILL:7DLU:NONE,RIGHT:DEFAULT:NONE,FILL:3DLU:NONE,FILL:DEFAULT:GROW(1.0),FILL:7DLU:NONE","CENTER:9DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:9DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:9DLU:NONE"); - CellConstraints cc = new CellConstraints(); - jpanel1.setLayout(formlayout1); - - _versionInfoCheck.setActionCommand("Add version information"); - _versionInfoCheck.setName("versionInfoCheck"); - _versionInfoCheck.setText(Messages.getString("addVersionInfo")); - jpanel1.add(_versionInfoCheck,cc.xywh(4,2,5,1)); - - _fileVersionLabel.setIcon(loadImage("images/asterix.gif")); - _fileVersionLabel.setName("fileVersionLabel"); - _fileVersionLabel.setText(Messages.getString("fileVersion")); - jpanel1.add(_fileVersionLabel,cc.xy(2,4)); - - _fileVersionField.setName("fileVersionField"); - _fileVersionField.setToolTipText(Messages.getString("fileVersionTip")); - jpanel1.add(_fileVersionField,cc.xy(4,4)); - - _addVersionInfoSeparator.setName("addVersionInfoSeparator"); - _addVersionInfoSeparator.setText("Additional information"); - jpanel1.add(_addVersionInfoSeparator,cc.xywh(2,10,7,1)); - - _productVersionLabel.setIcon(loadImage("images/asterix.gif")); - _productVersionLabel.setName("productVersionLabel"); - _productVersionLabel.setText(Messages.getString("productVersion")); - jpanel1.add(_productVersionLabel,cc.xy(2,12)); - - _productVersionField.setName("productVersionField"); - _productVersionField.setToolTipText(Messages.getString("productVersionTip")); - jpanel1.add(_productVersionField,cc.xy(4,12)); - - _fileDescriptionLabel.setIcon(loadImage("images/asterix.gif")); - _fileDescriptionLabel.setName("fileDescriptionLabel"); - _fileDescriptionLabel.setText(Messages.getString("fileDescription")); - jpanel1.add(_fileDescriptionLabel,cc.xy(2,6)); - - _fileDescriptionField.setName("fileDescriptionField"); - _fileDescriptionField.setToolTipText(Messages.getString("fileDescriptionTip")); - jpanel1.add(_fileDescriptionField,cc.xywh(4,6,5,1)); - - _copyrightLabel.setIcon(loadImage("images/asterix.gif")); - _copyrightLabel.setName("copyrightLabel"); - _copyrightLabel.setText(Messages.getString("copyright")); - jpanel1.add(_copyrightLabel,cc.xy(2,8)); - - _copyrightField.setName("copyrightField"); - jpanel1.add(_copyrightField,cc.xywh(4,8,5,1)); - - _txtFileVersionLabel.setIcon(loadImage("images/asterix.gif")); - _txtFileVersionLabel.setName("txtFileVersionLabel"); - _txtFileVersionLabel.setText(Messages.getString("txtFileVersion")); - jpanel1.add(_txtFileVersionLabel,cc.xy(6,4)); - - _txtFileVersionField.setName("txtFileVersionField"); - _txtFileVersionField.setToolTipText(Messages.getString("txtFileVersionTip")); - jpanel1.add(_txtFileVersionField,cc.xy(8,4)); - - _txtProductVersionLabel.setIcon(loadImage("images/asterix.gif")); - _txtProductVersionLabel.setName("txtProductVersionLabel"); - _txtProductVersionLabel.setText(Messages.getString("txtProductVersion")); - jpanel1.add(_txtProductVersionLabel,cc.xy(6,12)); - - _txtProductVersionField.setName("txtProductVersionField"); - _txtProductVersionField.setToolTipText(Messages.getString("txtProductVersionTip")); - jpanel1.add(_txtProductVersionField,cc.xy(8,12)); - - _productNameLabel.setIcon(loadImage("images/asterix.gif")); - _productNameLabel.setName("productNameLabel"); - _productNameLabel.setText(Messages.getString("productName")); - jpanel1.add(_productNameLabel,cc.xy(2,14)); - - _productNameField.setName("productNameField"); - jpanel1.add(_productNameField,cc.xywh(4,14,5,1)); - - _originalFilenameLabel.setIcon(loadImage("images/asterix.gif")); - _originalFilenameLabel.setName("originalFilenameLabel"); - _originalFilenameLabel.setText(Messages.getString("originalFilename")); - jpanel1.add(_originalFilenameLabel,cc.xy(2,20)); - - _originalFilenameField.setName("originalFilenameField"); - _originalFilenameField.setToolTipText(Messages.getString("originalFilenameTip")); - jpanel1.add(_originalFilenameField,cc.xywh(4,20,5,1)); - - _internalNameLabel.setIcon(loadImage("images/asterix.gif")); - _internalNameLabel.setName("internalNameLabel"); - _internalNameLabel.setText(Messages.getString("internalName")); - jpanel1.add(_internalNameLabel,cc.xy(2,18)); - - _internalNameField.setName("internalNameField"); - _internalNameField.setToolTipText(Messages.getString("internalNameTip")); - jpanel1.add(_internalNameField,cc.xywh(4,18,5,1)); - - _companyNameLabel.setName("companyNameLabel"); - _companyNameLabel.setText(Messages.getString("companyName")); - jpanel1.add(_companyNameLabel,cc.xy(2,16)); - - _companyNameField.setName("companyNameField"); - jpanel1.add(_companyNameField,cc.xywh(4,16,5,1)); - - addFillComponents(jpanel1,new int[]{ 1,2,3,4,5,6,7,8,9 },new int[]{ 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21 }); - return jpanel1; - } - - /** - * Initializer - */ - protected void initializePanel() - { - setLayout(new BorderLayout()); - add(createPanel(), BorderLayout.CENTER); - } - - -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/VersionInfoForm.jfrm b/build/windows/launcher/launch4j/src/net/sf/launch4j/form/VersionInfoForm.jfrm deleted file mode 100755 index 32eb136c880..00000000000 Binary files a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/VersionInfoForm.jfrm and /dev/null differ diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/messages.properties b/build/windows/launcher/launch4j/src/net/sf/launch4j/form/messages.properties deleted file mode 100755 index 1be6c9584f5..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/messages.properties +++ /dev/null @@ -1,146 +0,0 @@ -# -# Launch4j (http://launch4j.sourceforge.net/) -# Cross-platform Java application wrapper for creating Windows native executables. -# -# Copyright (c) 2004, 2007 Grzegorz Kowal -# -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without modification, -# are permitted provided that the following conditions are met: -# -# * Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# * Neither the name of the Launch4j nor the names of its contributors -# may be used to endorse or promote products derived from this software without -# specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# - -log=Log - -outfile=Output file: -outfileTip=Output executable file. -customProcName=Custom process name and XP style manifest -stayAlive=Stay alive after launching a GUI application -manifest=Manifest: -manifestTip=Wrapper's manifest for User Account Control, will not enable XP styles! -icon=Icon: -iconTip=Application icon. -jar=Jar: -jarTip=Application jar. -dontWrapJar=Dont't wrap the jar, launch only -cmdLine=Command line args: -cmdLineTip=Constant command line arguments passed to the application. -options=Options: -chdir=Change dir: -chdirTip=Change current directory to a location relative to the executable. Empty field has no effect, . - changes directory to the exe location. -priority=Process priority: -normalPriority=Normal -idlePriority=Idle -highPriority=High -downloadAndSupport=Java download and support -errorTitle=Error title: -errorTitleTip=Launch4j signals errors using a message box, you can set it's title to the application's name. -downloadUrl=Java download URL: -supportUrl=Support URL: - -new=New -accept=Accept -remove=Remove -customClassPath=Custom classpath -classPath=Classpath: -mainClass=Main class: -editClassPath=Edit item: -importClassPath=Import attributes from a jar's manifest. - -headerType=Header type: -gui=GUI -console=Console -objectFiles=Object files: -libs=w32api: -linkerOptions=Custom header - linker options - -enableSingleInstance=Allow only a single instance of the application -mutexName=Mutex name -mutexNameTip=Mutex name that will uniquely identify your application. -windowTitle=Window title -windowTitleTip=Title of the GUI application window to bring up on attempt to start a next instance. - -jrePath=Bundled JRE path: -jrePathTip=Bundled JRE path relative to the executable or absolute. -jreMin=Min JRE version: -jreMax=Max JRE version: -dontUsePrivateJres=Don't use private JREs -jvmOptions=JVM options: -jvmOptionsTip=Accepts everything you would normally pass to java/javaw launcher: assertion options, system properties and X options. -initialHeapSize=Initial heap size: -maxHeapSize=Max heap size: -freeMemory=% of free memory -jdkPreference=JDK/JRE preference: -addVariables=Add variables: -addVariablesTip=Add special variable or map environment variables to system properties. -exeDirVarTip=Executable's runtime directory path. -exeFileVarTip=Executable's runtime file path (directory and filename). -varsAndRegistry=Variables / registry: -envVar=Environment var: -property=Property -propertyTip=Map a variable to a system property. -option=Option -optionTip=Pass a JVM option using a variable. - -setVariables=Set variables: - -enableSplash=Enable splash screen -splashFile=Splash file: -splashFileTip=Splash screen file in BMP format. -waitForWindow=Wait for window -waitForWindowText=Close splash screen when an application window appears -timeout=Timeout [s]: -timeoutTip=Number of seconds after which the splash screen must close. Splash timeout may cause an error depending on splashTimeoutErr property. -timeoutErr=Signal error on timeout -timeoutErrTip=True signals an error on splash timeout, false closes the splash screen quietly. - -version=Version -additionalInfo=Additional information -addVersionInfo=Add version information -fileVersion=File version: -fileVersionTip=Version number 'x.x.x.x' -productVersion=Product version: -productVersionTip=Version number 'x.x.x.x' -fileDescription=File description: -fileDescriptionTip=File description presented to the user. -copyright=Copyright: -txtFileVersion=Free form: -txtFileVersionTip=Free form file version, for example '1.20.RC1'. -txtProductVersion=Free form: -txtProductVersionTip=Free form product version, for example '1.20.RC1'. -productName=Product name: -originalFilename=Original filename: -originalFilenameTip=Original name of the file without the path. Allows to determine whether a file has been renamed by a user. -internalName=Internal name: -internalNameTip=Internal name without extension, original filename or module name for example. -companyName=Company name: - -addMessages=Add custom messages -startupErr=Startup error: -bundledJreErr=Bundled JRE error: -jreVersionErr=JRE version error: -jreVersionErrTip=Launch4j will append the required version number at the end of this message. -launcherErr=Launcher error: -instanceAlreadyExistsMsg=Inst. already exists: -instanceAlreadyExistsMsgTip=Message displayed by single instance console applications if an instance already exists. diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/messages_es.properties b/build/windows/launcher/launch4j/src/net/sf/launch4j/form/messages_es.properties deleted file mode 100755 index 50e2d758715..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/form/messages_es.properties +++ /dev/null @@ -1,118 +0,0 @@ -# -# Launch4j (http://launch4j.sourceforge.net/) -# Cross-platform Java application wrapper for creating Windows native executables. -# -# Copyright (c) 2004, 2007 Grzegorz Kowal, Patricio Mart�nez Ros -# -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without modification, -# are permitted provided that the following conditions are met: -# -# * Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# * Neither the name of the Launch4j nor the names of its contributors -# may be used to endorse or promote products derived from this software without -# specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# - -log = Registro - -outfile = Fichero de salida -outfileTip = Fichero ejecutable de salida. -errorTitle = T\u00EDtulo de error -errorTitleTip = Launch4j indica los errores usando una ventana de mensaje, usted puede ponerle el nombre de la aplicaci\u00F3n a esta ventana. -customProcName = Nombre personalizado del proceso -stayAlive = Mantener abierto despu\u00E9s de lanzar una aplicaci\u00F3n GUI -icon = Icono -iconTip = Icono de la aplicaci\u00F3n. -jar = Jar -jarTip = Jar de la aplicaci\u00F3n. -dontWrapJar = No empaquetar el jar, s\u00F3lo lanzar -cmdLine = Argumentos del jar -cmdLine = Argumentos de l\u00EDnea de \u00F3rdenes pasados a la aplicaci\u00F3n. -options = Opciones -chdir = Cambiar al directorio -chdirTip = Cambia el directorio actual a la localizaci\u00F3n relativa al ejecutable. Si el campo se deja vac\u00EDo, no tiene efecto, . - cambia el directorio a la localizaci\u00F3n del exe. -headerType = Tipo de cabecera -gui = GUI -console = Consola -objectFiles = Ficheros objeto -libs = w32api -linkerOptions = Cabecera personalizada - opciones del enlazador -jrePath = Ruta del JRE -jrePathTip = Ruta relativa al ejecutable del JRE. -jreMin = Versi\u00F3n m\u00EDnima del JRE -jreMax = Versi\u00F3n m\u00E1xima del JRE -jvmOptions = Argumentos de la JVM -jvmOptionsTip = Acepta cualquier argumento que normalmente se le pasar\u00EDa al lanzador java/javaw\: opciones assertion, propiedades de sistema y opciones X. -initialHeapSize = Tama\u00F1o inicial de la pila -maxHeapSize = Tama\u00F1o m\u00E1ximo de la pila -freeMemory=% of free memory -addVariables = A\u00F1adir variables -addVariablesTip = A\u00F1adir una variable especial o mapear variables de entorno a las propiedades del sistema. -exeDirVarTip = Ruta del directorio del ejecutable. -exeFileVarTip = Ruta del fichero ejecutable (directorio y nombre del fichero). -other = Otra -otherTip = Mapear una variable de entorno a una propiedad del sistema. -otherVarTip = Variable de entorno que mapear. -add = A\u00F1adir -specifyVar = Especificar variable de entorno que a\u00F1adir. -enableSplash = Activar pantalla de bienvenida -splashFile = Imagen -splashFileTip = Imagen en formato BMP para la pantalla de bienvenida. -waitForWindow = Esperar la ventana -waitForWindowText = Cerrar la pantalla de bienvenida cuando aparezca una ventana de la aplicaci\u00F3n -timeout = Tiempo de espera [s] -timeoutTip = Numero de segundos despu\u00E9s de los que la pantalla de bienvenida se debe cerrar. Esta propiedad puede causar provocar un error dependiendo de la propiedad splashTimeoutErr. -timeoutErr = Se\u00F1al de error asociada al tiempo de espera -timeoutErrTip = Marcado (true) se\u00F1ala un error despu\u00E9s del tiempo de espera de la pantalla de bienvenida, no marcado (false) cierra la pantalla de bienvenida silenciosamente -addVersionInfo = A\u00F1ade informaci\u00F3n sobre la versi\u00F3n -fileVersion = Versi\u00F3n del fichero -fileVersionTip = N\u00FAmero de versi\u00F3n 'x.x.x.x' -additionalInfo = Informaci\u00F3n adicional -productVersion = Versi\u00F3n del producto -productVersionTip = N\u00FAmero de versi\u00F3n 'x.x.x.x' -fileDescription = Descripci\u00F3n del fichero -fileDescriptionTip = Descripci\u00F3n del fichero que se le muestra al usuario. -copyright = Copyright -txtFileVersion = Forma libre -txtFileVersionTip = Forma libre de versi\u00F3n, por ejemplo '1.20.RC1'. -txtProductVersion = Forma libre -txtProductVersionTip = Forma libre del producto, por ejemplo '1.20.RC1'. -productName = Nombre del producto -originalFilename = Nombre original del fichero -originalFilenameTip = Nombre original del fichero sin la ruta. Permite determinar si un fichero ha sido renombrado por un usuario. -internalName = Nombre interno -internalNameTip = Nombre interno sin extensi\u00F3n, el nombre original del fichero o el m\u00F3dulo, por ejemplo. -companyName = Nombre de la organizaci\u00F3n - -addMessages=Add custom messages -startupErr=Startup error: -bundledJreErr=Bundled JRE error: -jreVersionErr=JRE version error: -jreVersionErrTip=Launch4j will append the required version number at the end of this message. -launcherErr=Launcher error: -instanceAlreadyExistsMsg=Inst. already exists: -instanceAlreadyExistsMsgTip=Message displayed by single instance console applications if an instance already exists. - -enableSingleInstance=Allow only a single instance of the application -mutexName=Mutex name -mutexNameTip=Mutex name that will uniquely identify your application. -windowTitle=Window title -windowTitleTip=Title of the application window to bring up on attempt to start a next instance. diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/AbstractAcceptListener.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/AbstractAcceptListener.java deleted file mode 100755 index 5265e6436c3..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/AbstractAcceptListener.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on May 1, 2006 - */ -package net.sf.launch4j.formimpl; - -import java.awt.Color; -import java.awt.event.ActionListener; - -import javax.swing.JTextField; - -import net.sf.launch4j.binding.Binding; - -/** - * @author Copyright (C) 2006 Grzegorz Kowal - */ -public abstract class AbstractAcceptListener implements ActionListener { - final JTextField _field; - - public AbstractAcceptListener(JTextField f, boolean listen) { - _field = f; - if (listen) { - _field.addActionListener(this); - } - } - - protected String getText() { - return _field.getText(); - } - - protected void clear() { - _field.setText(""); - _field.requestFocusInWindow(); - } - - protected void signalViolation(String msg) { - final Color bg = _field.getBackground(); - _field.setBackground(Binding.INVALID_COLOR); - MainFrame.getInstance().warn(msg); - _field.setBackground(bg); - _field.requestFocusInWindow(); - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/BasicFormImpl.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/BasicFormImpl.java deleted file mode 100755 index 01ebe8adfb2..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/BasicFormImpl.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on May 1, 2006 - */ -package net.sf.launch4j.formimpl; - -import javax.swing.JFileChooser; -import javax.swing.JRadioButton; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import net.sf.launch4j.FileChooserFilter; -import net.sf.launch4j.binding.Bindings; -import net.sf.launch4j.config.Config; -import net.sf.launch4j.form.BasicForm; - -/** - * @author Copyright (C) 2006 Grzegorz Kowal - */ -public class BasicFormImpl extends BasicForm { - - public BasicFormImpl(Bindings bindings, JFileChooser fc) { - bindings.add("outfile", _outfileField) - .add("dontWrapJar", _dontWrapJarCheck) - .add("jar", _jarField) - .add("manifest", _manifestField) - .add("icon", _iconField) - .add("cmdLine", _cmdLineField) - .add("errTitle", _errorTitleField) - .add("downloadUrl", _downloadUrlField, Config.DOWNLOAD_URL) - .add("supportUrl", _supportUrlField) - .add("chdir", _chdirField) - .add("priorityIndex", new JRadioButton[] { _normalPriorityRadio, - _idlePriorityRadio, - _highPriorityRadio }) - .add("customProcName", _customProcNameCheck) - .add("stayAlive", _stayAliveCheck); - - _dontWrapJarCheck.addChangeListener(new DontWrapJarChangeListener()); - - _outfileButton.addActionListener(new BrowseActionListener(true, fc, - new FileChooserFilter("Windows executables (.exe)", ".exe"), - _outfileField)); - _jarButton.addActionListener(new BrowseActionListener(false, fc, - new FileChooserFilter("Jar files", ".jar"), _jarField)); - _manifestButton.addActionListener(new BrowseActionListener(false, fc, - new FileChooserFilter("Manifest files (.manifest)", ".manifest"), - _manifestField)); - _iconButton.addActionListener(new BrowseActionListener(false, fc, - new FileChooserFilter("Icon files (.ico)", ".ico"), _iconField)); - } - - private class DontWrapJarChangeListener implements ChangeListener { - - public void stateChanged(ChangeEvent e) { - boolean dontWrap = _dontWrapJarCheck.isSelected(); - if (dontWrap) { - _jarLabel.setIcon(loadImage("images/asterix-o.gif")); - _jarLabel.setText(Messages.getString("jarPath")); - _jarField.setToolTipText(Messages.getString("jarPathTip")); - } else { - _jarLabel.setIcon(loadImage("images/asterix.gif")); - _jarLabel.setText(Messages.getString("jar")); - _jarField.setToolTipText(Messages.getString("jarTip")); - } - _jarButton.setEnabled(!dontWrap); - } - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/BrowseActionListener.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/BrowseActionListener.java deleted file mode 100755 index 89a5017ee23..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/BrowseActionListener.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on May 1, 2006 - */ -package net.sf.launch4j.formimpl; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.File; - -import javax.swing.JFileChooser; -import javax.swing.JTextField; - -import net.sf.launch4j.FileChooserFilter; - -/** - * @author Copyright (C) 2006 Grzegorz Kowal - */ -public class BrowseActionListener implements ActionListener { - private final boolean _save; - private final JFileChooser _fileChooser; - private final FileChooserFilter _filter; - private final JTextField _field; - - public BrowseActionListener(boolean save, JFileChooser fileChooser, - FileChooserFilter filter, JTextField field) { - _save = save; - _fileChooser = fileChooser; - _filter = filter; - _field = field; - } - - public void actionPerformed(ActionEvent e) { - if (!_field.isEnabled()) { - return; - } - _fileChooser.setFileFilter(_filter); - _fileChooser.setSelectedFile(new File("")); - int result = _save - ? _fileChooser.showSaveDialog(MainFrame.getInstance()) - : _fileChooser.showOpenDialog(MainFrame.getInstance()); - if (result == JFileChooser.APPROVE_OPTION) { - _field.setText(_fileChooser.getSelectedFile().getPath()); - } - _fileChooser.removeChoosableFileFilter(_filter); - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/ClassPathFormImpl.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/ClassPathFormImpl.java deleted file mode 100755 index 65d82096ee3..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/ClassPathFormImpl.java +++ /dev/null @@ -1,222 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on May 1, 2006 - */ -package net.sf.launch4j.formimpl; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.File; -import java.io.IOException; -import java.util.jar.Attributes; -import java.util.jar.JarFile; - -import javax.swing.DefaultListModel; -import javax.swing.JFileChooser; -import javax.swing.JTextField; -import javax.swing.ListSelectionModel; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import net.sf.launch4j.FileChooserFilter; -import net.sf.launch4j.binding.Bindings; -import net.sf.launch4j.binding.Validator; -import net.sf.launch4j.config.ClassPath; -import net.sf.launch4j.form.ClassPathForm; - -/** - * @author Copyright (C) 2006 Grzegorz Kowal - */ -public class ClassPathFormImpl extends ClassPathForm { - private final JFileChooser _fileChooser; - private final FileChooserFilter _filter - = new FileChooserFilter("Executable jar", ".jar"); - - public ClassPathFormImpl(Bindings bindings, JFileChooser fc) { - bindings.addOptComponent("classPath", ClassPath.class, _classpathCheck) - .add("classPath.mainClass", _mainclassField) - .add("classPath.paths", _classpathList); - _fileChooser = fc; - - ClasspathCheckListener cpl = new ClasspathCheckListener(); - _classpathCheck.addChangeListener(cpl); - cpl.stateChanged(null); - - _classpathList.setModel(new DefaultListModel()); - _classpathList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); - _classpathList.addListSelectionListener(new ClasspathSelectionListener()); - - _newClasspathButton.addActionListener(new NewClasspathListener()); - _acceptClasspathButton.addActionListener( - new AcceptClasspathListener(_classpathField)); - _removeClasspathButton.addActionListener(new RemoveClasspathListener()); - _importClasspathButton.addActionListener(new ImportClasspathListener()); - _classpathUpButton.addActionListener(new MoveUpListener()); - _classpathDownButton.addActionListener(new MoveDownListener()); - } - - private class ClasspathCheckListener implements ChangeListener { - public void stateChanged(ChangeEvent e) { - boolean on = _classpathCheck.isSelected(); - _importClasspathButton.setEnabled(on); - _classpathUpButton.setEnabled(on); - _classpathDownButton.setEnabled(on); - _classpathField.setEnabled(on); - _newClasspathButton.setEnabled(on); - _acceptClasspathButton.setEnabled(on); - _removeClasspathButton.setEnabled(on); - } - } - - private class NewClasspathListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - _classpathList.clearSelection(); - _classpathField.setText(""); - _classpathField.requestFocusInWindow(); - } - } - - private class AcceptClasspathListener extends AbstractAcceptListener { - public AcceptClasspathListener(JTextField f) { - super(f, true); - } - - public void actionPerformed(ActionEvent e) { - String cp = getText(); - if (Validator.isEmpty(cp)) { - signalViolation(Messages.getString("specifyClassPath")); - return; - } - DefaultListModel model = (DefaultListModel) _classpathList.getModel(); - if (_classpathList.isSelectionEmpty()) { - model.addElement(cp); - clear(); - } else { - model.setElementAt(cp, _classpathList.getSelectedIndex()); - } - } - } - - private class ClasspathSelectionListener implements ListSelectionListener { - public void valueChanged(ListSelectionEvent e) { - if (e.getValueIsAdjusting()) { - return; - } - if (_classpathList.isSelectionEmpty()) { - _classpathField.setText(""); - } else { - _classpathField.setText((String) _classpathList.getSelectedValue()); - } - _classpathField.requestFocusInWindow(); - } - } - - private class RemoveClasspathListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - if (_classpathList.isSelectionEmpty() - || !MainFrame.getInstance().confirm( - Messages.getString("confirmClassPathRemoval"))) { - return; - } - DefaultListModel model = (DefaultListModel) _classpathList.getModel(); - while (!_classpathList.isSelectionEmpty()) { - model.remove(_classpathList.getSelectedIndex()); - } - } - } - - private class MoveUpListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - int x = _classpathList.getSelectedIndex(); - if (x < 1) { - return; - } - DefaultListModel model = (DefaultListModel) _classpathList.getModel(); - Object o = model.get(x - 1); - model.set(x - 1, model.get(x)); - model.set(x, o); - _classpathList.setSelectedIndex(x - 1); - } - } - - private class MoveDownListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - DefaultListModel model = (DefaultListModel) _classpathList.getModel(); - int x = _classpathList.getSelectedIndex(); - if (x == -1 || x >= model.getSize() - 1) { - return; - } - Object o = model.get(x + 1); - model.set(x + 1, model.get(x)); - model.set(x, o); - _classpathList.setSelectedIndex(x + 1); - } - } - - private class ImportClasspathListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - try { - _fileChooser.setFileFilter(_filter); - _fileChooser.setSelectedFile(new File("")); - if (_fileChooser.showOpenDialog(MainFrame.getInstance()) - == JFileChooser.APPROVE_OPTION) { - JarFile jar = new JarFile(_fileChooser.getSelectedFile()); - if (jar.getManifest() == null) { - jar.close(); - MainFrame.getInstance().info(Messages.getString("noManifest")); - return; - } - Attributes attr = jar.getManifest().getMainAttributes(); - String mainClass = (String) attr.getValue("Main-Class"); - String classPath = (String) attr.getValue("Class-Path"); - jar.close(); - _mainclassField.setText(mainClass != null ? mainClass : ""); - DefaultListModel model = new DefaultListModel(); - if (classPath != null) { - String[] paths = classPath.split(" "); - for (int i = 0; i < paths.length; i++) { - model.addElement(paths[i]); - } - } - _classpathList.setModel(model); - } - } catch (IOException ex) { - MainFrame.getInstance().warn(ex.getMessage()); - } - } - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/ConfigFormImpl.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/ConfigFormImpl.java deleted file mode 100755 index d29720642b5..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/ConfigFormImpl.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on May 10, 2005 - */ -package net.sf.launch4j.formimpl; - -import javax.swing.BorderFactory; -import javax.swing.JFileChooser; -import javax.swing.JTextArea; - -import net.sf.launch4j.binding.Binding; -import net.sf.launch4j.binding.Bindings; -import net.sf.launch4j.binding.IValidatable; -import net.sf.launch4j.form.ConfigForm; - -/** - * @author Copyright (C) 2005 Grzegorz Kowal - */ -public class ConfigFormImpl extends ConfigForm { - private final Bindings _bindings = new Bindings(); - private final JFileChooser _fileChooser = new FileChooser(ConfigFormImpl.class); - - public ConfigFormImpl() { - _tab.setBorder(BorderFactory.createMatteBorder(0, -1, -1, -1, getBackground())); - _tab.addTab(Messages.getString("tab.basic"), - new BasicFormImpl(_bindings, _fileChooser)); - _tab.addTab(Messages.getString("tab.classpath"), - new ClassPathFormImpl(_bindings, _fileChooser)); - _tab.addTab(Messages.getString("tab.header"), - new HeaderFormImpl(_bindings)); - _tab.addTab(Messages.getString("tab.singleInstance"), - new SingleInstanceFormImpl(_bindings)); - _tab.addTab(Messages.getString("tab.jre"), - new JreFormImpl(_bindings, _fileChooser)); - _tab.addTab(Messages.getString("tab.envVars"), - new EnvironmentVarsFormImpl(_bindings)); - _tab.addTab(Messages.getString("tab.splash"), - new SplashFormImpl(_bindings, _fileChooser)); - _tab.addTab(Messages.getString("tab.version"), - new VersionInfoFormImpl(_bindings, _fileChooser)); - _tab.addTab(Messages.getString("tab.messages"), - new MessagesFormImpl(_bindings)); - } - - public void clear(IValidatable bean) { - _bindings.clear(bean); - } - - public void put(IValidatable bean) { - _bindings.put(bean); - } - - public void get(IValidatable bean) { - _bindings.get(bean); - } - - public boolean isModified() { - return _bindings.isModified(); - } - - public JTextArea getLogTextArea() { - return _logTextArea; - } - - public Binding getBinding(String property) { - return _bindings.getBinding(property); - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/EnvironmentVarsFormImpl.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/EnvironmentVarsFormImpl.java deleted file mode 100755 index 2f325fe3cf9..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/EnvironmentVarsFormImpl.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on Jun 10, 2006 - */ -package net.sf.launch4j.formimpl; - -import net.sf.launch4j.binding.Bindings; -import net.sf.launch4j.form.EnvironmentVarsForm; - -/** - * @author Copyright (C) 2006 Grzegorz Kowal - */ -public class EnvironmentVarsFormImpl extends EnvironmentVarsForm { - - public EnvironmentVarsFormImpl(Bindings bindings) { - bindings.add("variables", _envVarsTextArea); - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/FileChooser.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/FileChooser.java deleted file mode 100755 index c1b984e5878..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/FileChooser.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on Jul 19, 2006 - */ -package net.sf.launch4j.formimpl; - -import java.io.File; -import java.util.prefs.Preferences; - -import javax.swing.JFileChooser; - -/** - * @author Copyright (C) 2006 Grzegorz Kowal - */ -public class FileChooser extends JFileChooser { - private final Preferences _prefs; - private final String _key; - - public FileChooser(Class clazz) { - _prefs = Preferences.userNodeForPackage(clazz); - _key = "currentDir-" - + clazz.getName().substring(clazz.getName().lastIndexOf('.') + 1); - String path = _prefs.get(_key, null); - if (path != null) { - setCurrentDirectory(new File(path)); - } - } - - public void approveSelection() { - _prefs.put(_key, getCurrentDirectory().getPath()); - super.approveSelection(); - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/GlassPane.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/GlassPane.java deleted file mode 100755 index c1b1d8dd4f0..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/GlassPane.java +++ /dev/null @@ -1,67 +0,0 @@ -package net.sf.launch4j.formimpl; - -import java.awt.AWTEvent; -import java.awt.Component; -import java.awt.Cursor; -import java.awt.Toolkit; -import java.awt.Window; -import java.awt.event.AWTEventListener; -import java.awt.event.KeyAdapter; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; - -import javax.swing.JComponent; -import javax.swing.SwingUtilities; - -/** - * This is the glass pane class that intercepts screen interactions during - * system busy states. - * - * Based on JavaWorld article by Yexin Chen. - */ -public class GlassPane extends JComponent implements AWTEventListener { - private final Window _window; - - public GlassPane(Window w) { - _window = w; - addMouseListener(new MouseAdapter() {}); - addKeyListener(new KeyAdapter() {}); - setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); - } - - /** - * Receives all key events in the AWT and processes the ones that originated - * from the current window with the glass pane. - * - * @param event - * the AWTEvent that was fired - */ - public void eventDispatched(AWTEvent event) { - Object source = event.getSource(); - if (event instanceof KeyEvent - && source instanceof Component) { - /* - * If the event originated from the window w/glass pane, - * consume the event. - */ - if ((SwingUtilities.windowForComponent((Component) source) == _window)) { - ((KeyEvent) event).consume(); - } - } - } - - /** - * Sets the glass pane as visible or invisible. The mouse cursor will be set - * accordingly. - */ - public void setVisible(boolean visible) { - if (visible) { - // Start receiving all events and consume them if necessary - Toolkit.getDefaultToolkit().addAWTEventListener(this, AWTEvent.KEY_EVENT_MASK); - } else { - // Stop receiving all events - Toolkit.getDefaultToolkit().removeAWTEventListener(this); - } - super.setVisible(visible); - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/HeaderFormImpl.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/HeaderFormImpl.java deleted file mode 100755 index accfaa9de50..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/HeaderFormImpl.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on May 1, 2006 - */ -package net.sf.launch4j.formimpl; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.JRadioButton; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import net.sf.launch4j.binding.Binding; -import net.sf.launch4j.binding.Bindings; -import net.sf.launch4j.config.Config; -import net.sf.launch4j.config.ConfigPersister; -import net.sf.launch4j.form.HeaderForm; - -/** - * @author Copyright (C) 2006 Grzegorz Kowal - */ -public class HeaderFormImpl extends HeaderForm { - private final Bindings _bindings; - - public HeaderFormImpl(Bindings bindings) { - _bindings = bindings; - _bindings.add("headerTypeIndex", new JRadioButton[] { _guiHeaderRadio, - _consoleHeaderRadio }) - .add("headerObjects", "customHeaderObjects", _headerObjectsCheck, - _headerObjectsTextArea) - .add("libs", "customLibs", _libsCheck, _libsTextArea); - - _guiHeaderRadio.addChangeListener(new HeaderTypeChangeListener()); - _headerObjectsCheck.addActionListener(new HeaderObjectsActionListener()); - _libsCheck.addActionListener(new LibsActionListener()); - } - - private class HeaderTypeChangeListener implements ChangeListener { - public void stateChanged(ChangeEvent e) { - Config c = ConfigPersister.getInstance().getConfig(); - c.setHeaderType(_guiHeaderRadio.isSelected() ? Config.GUI_HEADER - : Config.CONSOLE_HEADER); - if (!_headerObjectsCheck.isSelected()) { - Binding b = _bindings.getBinding("headerObjects"); - b.put(c); - } - } - } - - private class HeaderObjectsActionListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - if (!_headerObjectsCheck.isSelected()) { - ConfigPersister.getInstance().getConfig().setHeaderObjects(null); - Binding b = _bindings.getBinding("headerObjects"); - b.put(ConfigPersister.getInstance().getConfig()); - } - } - } - - private class LibsActionListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - if (!_libsCheck.isSelected()) { - ConfigPersister.getInstance().getConfig().setLibs(null); - Binding b = _bindings.getBinding("libs"); - b.put(ConfigPersister.getInstance().getConfig()); - } - } - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/JreFormImpl.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/JreFormImpl.java deleted file mode 100755 index 48a2f18e837..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/JreFormImpl.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on May 1, 2006 - */ -package net.sf.launch4j.formimpl; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.DefaultComboBoxModel; -import javax.swing.JFileChooser; -import javax.swing.JTextField; - -import net.sf.launch4j.binding.Bindings; -import net.sf.launch4j.binding.Validator; -import net.sf.launch4j.form.JreForm; -import net.sf.launch4j.config.Jre; - -/** - * @author Copyright (C) 2006 Grzegorz Kowal - */ -public class JreFormImpl extends JreForm { - - public JreFormImpl(Bindings bindings, JFileChooser fc) { - _jdkPreferenceCombo.setModel(new DefaultComboBoxModel(new String[] { - Messages.getString("jdkPreference.jre.only"), - Messages.getString("jdkPreference.prefer.jre"), - Messages.getString("jdkPreference.prefer.jdk"), - Messages.getString("jdkPreference.jdk.only")})); - bindings.add("jre.path", _jrePathField) - .add("jre.minVersion", _jreMinField) - .add("jre.maxVersion", _jreMaxField) - .add("jre.jdkPreferenceIndex", _jdkPreferenceCombo, - Jre.DEFAULT_JDK_PREFERENCE_INDEX) - .add("jre.initialHeapSize", _initialHeapSizeField) - .add("jre.initialHeapPercent", _initialHeapPercentField) - .add("jre.maxHeapSize", _maxHeapSizeField) - .add("jre.maxHeapPercent", _maxHeapPercentField) - .add("jre.options", _jvmOptionsTextArea); - - _varCombo.setModel(new DefaultComboBoxModel(new String[] { - "EXEDIR", "EXEFILE", "PWD", "OLDPWD", - "HKEY_CLASSES_ROOT", "HKEY_CURRENT_USER", "HKEY_LOCAL_MACHINE", - "HKEY_USERS", "HKEY_CURRENT_CONFIG" })); - - _varCombo.addActionListener(new VarComboActionListener()); - _varCombo.setSelectedIndex(0); - - _propertyButton.addActionListener(new PropertyActionListener()); - _optionButton.addActionListener(new OptionActionListener()); - - _envPropertyButton.addActionListener(new EnvPropertyActionListener(_envVarField)); - _envOptionButton.addActionListener(new EnvOptionActionListener(_envVarField)); - } - - private class VarComboActionListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - _optionButton.setEnabled(((String) _varCombo.getSelectedItem()) - .startsWith("HKEY_")); - } - } - - private class PropertyActionListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - final int pos = _jvmOptionsTextArea.getCaretPosition(); - final String var = (String) _varCombo.getSelectedItem(); - if (var.startsWith("HKEY_")) { - _jvmOptionsTextArea.insert("-Dreg.key=\"%" - + var + "\\\\...%\"\n", pos); - } else { - _jvmOptionsTextArea.insert("-Dlaunch4j." + var.toLowerCase() - + "=\"%" + var + "%\"\n", pos); - } - } - } - - private class OptionActionListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - final int pos = _jvmOptionsTextArea.getCaretPosition(); - final String var = (String) _varCombo.getSelectedItem(); - if (var.startsWith("HKEY_")) { - _jvmOptionsTextArea.insert("%" + var + "\\\\...%\n", pos); - } else { - _jvmOptionsTextArea.insert("%" + var + "%\n", pos); - } - } - } - - private abstract class EnvActionListener extends AbstractAcceptListener { - public EnvActionListener(JTextField f, boolean listen) { - super(f, listen); - } - - public void actionPerformed(ActionEvent e) { - final int pos = _jvmOptionsTextArea.getCaretPosition(); - final String var = getText() - .replaceAll("\"", "") - .replaceAll("%", ""); - if (Validator.isEmpty(var)) { - signalViolation(Messages.getString("specifyVar")); - return; - } - add(var, pos); - clear(); - } - - protected abstract void add(String var, int pos); - } - - private class EnvPropertyActionListener extends EnvActionListener { - public EnvPropertyActionListener(JTextField f) { - super(f, true); - } - - protected void add(String var, int pos) { - final String prop = var - .replaceAll(" ", ".") - .replaceAll("_", ".") - .toLowerCase(); - _jvmOptionsTextArea.insert("-Denv." + prop + "=\"%" + var - + "%\"\n", pos); - } - } - - private class EnvOptionActionListener extends EnvActionListener { - public EnvOptionActionListener(JTextField f) { - super(f, false); - } - - protected void add(String var, int pos) { - _jvmOptionsTextArea.insert("%" + var + "%\n", pos); - } - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/MainFrame.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/MainFrame.java deleted file mode 100755 index 4a2cc871596..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/MainFrame.java +++ /dev/null @@ -1,358 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on 2005-05-09 - */ -package net.sf.launch4j.formimpl; - -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.Toolkit; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.File; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JFileChooser; -import javax.swing.JFrame; -import javax.swing.JOptionPane; -import javax.swing.JToolBar; -import javax.swing.UIManager; - -import com.jgoodies.looks.Options; -import com.jgoodies.looks.plastic.PlasticXPLookAndFeel; - -import foxtrot.Task; -import foxtrot.Worker; - -import net.sf.launch4j.Builder; -import net.sf.launch4j.BuilderException; -import net.sf.launch4j.ExecException; -import net.sf.launch4j.FileChooserFilter; -import net.sf.launch4j.Log; -import net.sf.launch4j.Main; -import net.sf.launch4j.Util; -import net.sf.launch4j.binding.Binding; -import net.sf.launch4j.binding.BindingException; -import net.sf.launch4j.binding.InvariantViolationException; -import net.sf.launch4j.config.Config; -import net.sf.launch4j.config.ConfigPersister; -import net.sf.launch4j.config.ConfigPersisterException; - -/** - * @author Copyright (C) 2005 Grzegorz Kowal - */ -public class MainFrame extends JFrame { - private static MainFrame _instance; - - private final JToolBar _toolBar; - private final JButton _runButton; - private final ConfigFormImpl _configForm; - private final JFileChooser _fileChooser = new FileChooser(MainFrame.class); - private File _outfile; - private boolean _saved = false; - - public static void createInstance() { - try { - Toolkit.getDefaultToolkit().setDynamicLayout(true); - System.setProperty("sun.awt.noerasebackground","true"); - - // JGoodies - Options.setDefaultIconSize(new Dimension(16, 16)); // menu icons - Options.setUseNarrowButtons(false); - Options.setPopupDropShadowEnabled(true); - - UIManager.setLookAndFeel(new PlasticXPLookAndFeel()); - _instance = new MainFrame(); - } catch (Exception e) { - System.err.println(e); - } - } - - public static MainFrame getInstance() { - return _instance; - } - - public MainFrame() { - showConfigName(null); - setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); - addWindowListener(new MainFrameListener()); - setGlassPane(new GlassPane(this)); - _fileChooser.setFileFilter(new FileChooserFilter( - Messages.getString("MainFrame.config.files"), - new String[] {".xml", ".cfg"})); - - _toolBar = new JToolBar(); - _toolBar.setFloatable(false); - _toolBar.setRollover(true); - addButton("images/new.png", Messages.getString("MainFrame.new.config"), - new NewActionListener()); - addButton("images/open.png", Messages.getString("MainFrame.open.config"), - new OpenActionListener()); - addButton("images/save.png", Messages.getString("MainFrame.save.config"), - new SaveActionListener()); - _toolBar.addSeparator(); - addButton("images/build.png", Messages.getString("MainFrame.build.wrapper"), - new BuildActionListener()); - _runButton = addButton("images/run.png", - Messages.getString("MainFrame.test.wrapper"), - new RunActionListener()); - setRunEnabled(false); - _toolBar.addSeparator(); - addButton("images/info.png", Messages.getString("MainFrame.about.launch4j"), - new AboutActionListener()); - - _configForm = new ConfigFormImpl(); - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(_toolBar, BorderLayout.NORTH); - getContentPane().add(_configForm, BorderLayout.CENTER); - pack(); - Dimension scr = Toolkit.getDefaultToolkit().getScreenSize(); - Dimension fr = getSize(); - fr.width += 25; - fr.height += 100; - setBounds((scr.width - fr.width) / 2, (scr.height - fr.height) / 2, - fr.width, fr.height); - setVisible(true); - } - - private JButton addButton(String iconPath, String tooltip, ActionListener l) { - ImageIcon icon = new ImageIcon(MainFrame.class.getClassLoader() - .getResource(iconPath)); - JButton b = new JButton(icon); - b.setToolTipText(tooltip); - b.addActionListener(l); - _toolBar.add(b); - return b; - } - - public void info(String text) { - JOptionPane.showMessageDialog(this, - text, - Main.getName(), - JOptionPane.INFORMATION_MESSAGE); - } - - public void warn(String text) { - JOptionPane.showMessageDialog(this, - text, - Main.getName(), - JOptionPane.WARNING_MESSAGE); - } - - public void warn(InvariantViolationException e) { - Binding b = e.getBinding(); - if (b != null) { - b.markInvalid(); - } - warn(e.getMessage()); - if (b != null) { - e.getBinding().markValid(); - } - } - - public boolean confirm(String text) { - return JOptionPane.showConfirmDialog(MainFrame.this, - text, - Messages.getString("MainFrame.confirm"), - JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION; - } - - private boolean isModified() { - return (!_configForm.isModified()) - || confirm(Messages.getString("MainFrame.discard.changes")); - } - - private boolean save() { - // XXX - try { - _configForm.get(ConfigPersister.getInstance().getConfig()); - if (_fileChooser.showSaveDialog(MainFrame.this) == JOptionPane.YES_OPTION) { - File f = _fileChooser.getSelectedFile(); - if (!f.getPath().endsWith(".xml")) { - f = new File(f.getPath() + ".xml"); - } - ConfigPersister.getInstance().save(f); - _saved = true; - showConfigName(f); - return true; - } - return false; - } catch (InvariantViolationException ex) { - warn(ex); - return false; - } catch (BindingException ex) { - warn(ex.getMessage()); - return false; - } catch (ConfigPersisterException ex) { - warn(ex.getMessage()); - return false; - } - } - - private void showConfigName(File config) { - setTitle(Main.getName() + " - " + (config != null ? config.getName() - : Messages.getString("MainFrame.untitled"))); - } - - private void setRunEnabled(boolean enabled) { - if (!enabled) { - _outfile = null; - } - _runButton.setEnabled(enabled); - } - - private void clearConfig() { - ConfigPersister.getInstance().createBlank(); - _configForm.clear(ConfigPersister.getInstance().getConfig()); - } - - private class MainFrameListener extends WindowAdapter { - public void windowOpened(WindowEvent e) { - clearConfig(); - } - - public void windowClosing(WindowEvent e) { - if (isModified()) { - System.exit(0); - } - } - } - - private class NewActionListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - if (isModified()) { - clearConfig(); - } - _saved = false; - showConfigName(null); - setRunEnabled(false); - } - } - - private class OpenActionListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - try { - if (isModified() && _fileChooser.showOpenDialog(MainFrame.this) - == JOptionPane.YES_OPTION) { - final File f = _fileChooser.getSelectedFile(); - if (f.getPath().endsWith(".xml")) { - ConfigPersister.getInstance().load(f); - _saved = true; - } else { - ConfigPersister.getInstance().loadVersion1(f); - _saved = false; - } - _configForm.put(ConfigPersister.getInstance().getConfig()); - showConfigName(f); - setRunEnabled(false); - } - } catch (ConfigPersisterException ex) { - warn(ex.getMessage()); - } catch (BindingException ex) { - warn(ex.getMessage()); - } - } - } - - private class SaveActionListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - save(); - } - } - - private class BuildActionListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - final Log log = Log.getSwingLog(_configForm.getLogTextArea()); - try { - if ((!_saved || _configForm.isModified()) - && !save()) { - return; - } - log.clear(); - ConfigPersister.getInstance().getConfig().checkInvariants(); - Builder b = new Builder(log); - _outfile = b.build(); - setRunEnabled(ConfigPersister.getInstance().getConfig() - .getHeaderType() == Config.GUI_HEADER // TODO fix console app test - && (Util.WINDOWS_OS || !ConfigPersister.getInstance() - .getConfig().isDontWrapJar())); - } catch (InvariantViolationException ex) { - setRunEnabled(false); - ex.setBinding(_configForm.getBinding(ex.getProperty())); - warn(ex); - } catch (BuilderException ex) { - setRunEnabled(false); - log.append(ex.getMessage()); - } - } - } - - private class RunActionListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - try { - getGlassPane().setVisible(true); - Worker.post(new Task() { - public Object run() throws ExecException { - Log log = Log.getSwingLog(_configForm.getLogTextArea()); - log.clear(); - String path = _outfile.getPath(); - if (Util.WINDOWS_OS) { - log.append(Messages.getString("MainFrame.executing") + path); - Util.exec(new String[] { path }, log); - } else { - log.append(Messages.getString("MainFrame.jar.integrity.test") - + path); - Util.exec(new String[] { "java", "-jar", path }, log); - } - return null; - } - }); - } catch (Exception ex) { - // XXX errors logged by exec - } finally { - getGlassPane().setVisible(false); - } - }; - } - - private class AboutActionListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - info(Main.getDescription()); - } - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/Messages.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/Messages.java deleted file mode 100755 index 5e1c64110db..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/Messages.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -package net.sf.launch4j.formimpl; - -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -public class Messages { - private static final String BUNDLE_NAME = "net.sf.launch4j.formimpl.messages"; - - private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle - .getBundle(BUNDLE_NAME); - - private Messages() { - } - - public static String getString(String key) { - try { - return RESOURCE_BUNDLE.getString(key); - } catch (MissingResourceException e) { - return '!' + key + '!'; - } - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/MessagesFormImpl.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/MessagesFormImpl.java deleted file mode 100755 index c05d7f0474d..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/MessagesFormImpl.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on Oct 7, 2006 - */ -package net.sf.launch4j.formimpl; - -import net.sf.launch4j.binding.Bindings; -import net.sf.launch4j.config.Msg; -import net.sf.launch4j.form.MessagesForm; - -/** - * @author Copyright (C) 2006 Grzegorz Kowal - */ -public class MessagesFormImpl extends MessagesForm { - - public MessagesFormImpl(Bindings bindings) { - Msg m = new Msg(); - bindings.addOptComponent("messages", Msg.class, _messagesCheck) - .add("messages.startupErr", _startupErrTextArea, m.getStartupErr()) - .add("messages.bundledJreErr", _bundledJreErrTextArea, m.getBundledJreErr()) - .add("messages.jreVersionErr", _jreVersionErrTextArea, m.getJreVersionErr()) - .add("messages.launcherErr", _launcherErrTextArea, m.getLauncherErr()) - .add("messages.instanceAlreadyExistsMsg", _instanceAlreadyExistsMsgTextArea, - m.getInstanceAlreadyExistsMsg()); - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/SingleInstanceFormImpl.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/SingleInstanceFormImpl.java deleted file mode 100755 index c916a9184b5..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/SingleInstanceFormImpl.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/** - * Created on 2007-09-22 - */ -package net.sf.launch4j.formimpl; - -import net.sf.launch4j.binding.Bindings; -import net.sf.launch4j.config.SingleInstance; -import net.sf.launch4j.form.SingleInstanceForm; - -/** - * @author Copyright (C) 2007 Grzegorz Kowal - */ -public class SingleInstanceFormImpl extends SingleInstanceForm { - - public SingleInstanceFormImpl(Bindings bindings) { - bindings.addOptComponent("singleInstance", SingleInstance.class, - _singleInstanceCheck) - .add("singleInstance.mutexName", _mutexNameField) - .add("singleInstance.windowTitle", _windowTitleField); - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/SplashFormImpl.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/SplashFormImpl.java deleted file mode 100755 index 7413d4a213f..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/SplashFormImpl.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on May 1, 2006 - */ -package net.sf.launch4j.formimpl; - -import javax.swing.JFileChooser; - -import net.sf.launch4j.FileChooserFilter; -import net.sf.launch4j.binding.Bindings; -import net.sf.launch4j.config.Splash; -import net.sf.launch4j.form.SplashForm; - -/** - * @author Copyright (C) 2006 Grzegorz Kowal - */ -public class SplashFormImpl extends SplashForm { - - public SplashFormImpl(Bindings bindings, JFileChooser fc) { - bindings.addOptComponent("splash", Splash.class, _splashCheck) - .add("splash.file", _splashFileField) - .add("splash.waitForWindow", _waitForWindowCheck, true) - .add("splash.timeout", _timeoutField, "60") - .add("splash.timeoutErr", _timeoutErrCheck, true); - - _splashFileButton.addActionListener(new BrowseActionListener(false, fc, - new FileChooserFilter("Bitmap files (.bmp)", ".bmp"), _splashFileField)); - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/VersionInfoFormImpl.java b/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/VersionInfoFormImpl.java deleted file mode 100755 index c2f60d1d38a..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/VersionInfoFormImpl.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - Launch4j (http://launch4j.sourceforge.net/) - Cross-platform Java application wrapper for creating Windows native executables. - - Copyright (c) 2004, 2007 Grzegorz Kowal - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Launch4j nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Created on May 1, 2006 - */ -package net.sf.launch4j.formimpl; - -import javax.swing.JFileChooser; - -import net.sf.launch4j.binding.Bindings; -import net.sf.launch4j.config.VersionInfo; -import net.sf.launch4j.form.VersionInfoForm; - -/** - * @author Copyright (C) 2006 Grzegorz Kowal - */ -public class VersionInfoFormImpl extends VersionInfoForm { - - public VersionInfoFormImpl(Bindings bindings, JFileChooser fc) { - bindings.addOptComponent("versionInfo", VersionInfo.class, _versionInfoCheck) - .add("versionInfo.fileVersion", _fileVersionField) - .add("versionInfo.productVersion", _productVersionField) - .add("versionInfo.fileDescription", _fileDescriptionField) - .add("versionInfo.internalName", _internalNameField) - .add("versionInfo.originalFilename", _originalFilenameField) - .add("versionInfo.productName", _productNameField) - .add("versionInfo.txtFileVersion", _txtFileVersionField) - .add("versionInfo.txtProductVersion", _txtProductVersionField) - .add("versionInfo.companyName", _companyNameField) - .add("versionInfo.copyright", _copyrightField); - } -} diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/messages.properties b/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/messages.properties deleted file mode 100755 index 53a2442a886..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/messages.properties +++ /dev/null @@ -1,74 +0,0 @@ -# -# Launch4j (http://launch4j.sourceforge.net/) -# Cross-platform Java application wrapper for creating Windows native executables. -# -# Copyright (c) 2004, 2007 Grzegorz Kowal -# -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without modification, -# are permitted provided that the following conditions are met: -# -# * Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# * Neither the name of the Launch4j nor the names of its contributors -# may be used to endorse or promote products derived from this software without -# specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# - -tab.basic=Basic -tab.classpath=Classpath -tab.header=Header -tab.singleInstance=Single instance -tab.jre=JRE -tab.envVars=Set env. variables -tab.splash=Splash -tab.version=Version Info -tab.messages=Messages - -# Basic -jar=Jar: -jarPath=Jar runtime path: -jarTip=Application jar. -jarPathTip=Optional runtime path of the jar relative to the executable. For example, if the executable launcher and the application jar named calc.exe and calc.jar are in the same directory, it would be: calc.jar. - -# Classpath -specifyClassPath=Specify classpath item to add. -confirmClassPathRemoval=Remove selected classpath items? -noManifest=The selected jar does not have a manifest. - -# JRE -specifyVar=Specify environment variable to add. -otherVar=Other var -jdkPreference.jre.only=Only use public JREs -jdkPreference.prefer.jre=Prefer public JRE, but use JDK runtime if newer -jdkPreference.prefer.jdk=Prefer JDK runtime, but use public JRE if newer -jdkPreference.jdk.only=Only use private JDK runtimes - -MainFrame.config.files=launch4j config files (.xml, .cfg) -MainFrame.new.config=New configuration -MainFrame.open.config=Open configuration or import 1.x -MainFrame.save.config=Save configuration -MainFrame.build.wrapper=Build wrapper -MainFrame.test.wrapper=Test wrapper -MainFrame.about.launch4j=About launch4j -MainFrame.discard.changes=Discard changes? -MainFrame.confirm=Confirm -MainFrame.untitled=untitled -MainFrame.executing=Executing: -MainFrame.jar.integrity.test=Jar integrity test, executing: diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/messages_es.properties b/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/messages_es.properties deleted file mode 100755 index 1d2fac25f5f..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/formimpl/messages_es.properties +++ /dev/null @@ -1,56 +0,0 @@ -# -# Launch4j (http://launch4j.sourceforge.net/) -# Cross-platform Java application wrapper for creating Windows native executables. -# -# Copyright (c) 2004, 2007 Grzegorz Kowal, Patricio Mart�nez Ros -# -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without modification, -# are permitted provided that the following conditions are met: -# -# * Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# * Neither the name of the Launch4j nor the names of its contributors -# may be used to endorse or promote products derived from this software without -# specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# - -tab.basic = B\u00E1sico -tab.header = Cabecera -tab.jre = JRE -tab.splash = Pantalla de bienvenida -tab.version = Informaci\u00F3n de la versi\u00F3n - -jar = Jar -jarPath = Ruta del jar -jarTip = Jar de la aplicaci\u00F3n. -jarPathTip = Ruta del jar relativa al ejecutable. Por ejemplo, si el lanzador ejecutable y el jar de la aplicaci\u00F3n, llamados calc.exe y calc.jar respectivamente, est\u00E1n en el mismo directorio, ser\u00EDa\: calc.jar. - -MainFrame.config.files = Ficheros de configuraci\u00F3n de launch4j (.xml, .cfg) -MainFrame.new.config = Nueva configuraci\u00F3n -MainFrame.open.config = Abrir configuraci\u00F3n o importar 1.x -MainFrame.save.config = Guardar configuraci\u00F3n -MainFrame.build.wrapper = Construir el empaquetador -MainFrame.test.wrapper = Comprobar el empaquetador -MainFrame.about.launch4j = Acerca de launch4j -MainFrame.discard.changes = \u00BFDescartar cambios? -MainFrame.confirm = Confirmar -MainFrame.untitled = Sin nombre -MainFrame.executing = Ejecutando\: -MainFrame.jar.integrity.test = Prueba de integridad jar, ejecutando\: diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/messages.properties b/build/windows/launcher/launch4j/src/net/sf/launch4j/messages.properties deleted file mode 100755 index cf28d15afd4..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/messages.properties +++ /dev/null @@ -1,45 +0,0 @@ -# -# Launch4j (http://launch4j.sourceforge.net/) -# Cross-platform Java application wrapper for creating Windows native executables. -# -# Copyright (c) 2004, 2007 Grzegorz Kowal -# -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without modification, -# are permitted provided that the following conditions are met: -# -# * Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# * Neither the name of the Launch4j nor the names of its contributors -# may be used to endorse or promote products derived from this software without -# specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# - -Main.usage=usage - -Builder.compiling.resources=Compiling resources -Builder.linking=Linking -Builder.wrapping=Wrapping -Builder.success=Successfully created -Builder.generated.resource.file=Generated resource file...\n -Builder.line.has.errors=Line {0} has errors... - -Util.exec.failed=Exec failed -Util.tmpdir=Temporary file directory path (launch4j.tmpdir) cannot contain spaces. -Util.use.double.backslash=Use \\\\ to code Windows paths in fields that don't represent files or paths! diff --git a/build/windows/launcher/launch4j/src/net/sf/launch4j/messages_es.properties b/build/windows/launcher/launch4j/src/net/sf/launch4j/messages_es.properties deleted file mode 100755 index b179d9bd511..00000000000 --- a/build/windows/launcher/launch4j/src/net/sf/launch4j/messages_es.properties +++ /dev/null @@ -1,45 +0,0 @@ -# -# Launch4j (http://launch4j.sourceforge.net/) -# Cross-platform Java application wrapper for creating Windows native executables. -# -# Copyright (c) 2004, 2007 Grzegorz Kowal, Patricio Mart�nez Ros -# -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without modification, -# are permitted provided that the following conditions are met: -# -# * Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# * Neither the name of the Launch4j nor the names of its contributors -# may be used to endorse or promote products derived from this software without -# specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# - -Main.usage=Uso - -Builder.compiling.resources=Compilando recursos -Builder.linking=Enlazando -Builder.wrapping=Empaquetando -Builder.success=Creado con \ufffdxito -Builder.generated.resource.file=Fichero de recursos generado...\n -Builder.line.has.errors=Line {0} has errors... - -Util.exec.failed=Fallo en la ejecuci\ufffd -Util.tmpdir=Temporary file directory path (launch4j.tmpdir) cannot contain spaces. -Util.use.double.backslash=Use \\\\ to code Windows paths in fields that don't represent files or paths! \ No newline at end of file diff --git a/build/windows/launcher/launch4j/w32api/MinGW.LICENSE.txt b/build/windows/launcher/launch4j/w32api/MinGW.LICENSE.txt deleted file mode 100755 index 141412dd9f1..00000000000 --- a/build/windows/launcher/launch4j/w32api/MinGW.LICENSE.txt +++ /dev/null @@ -1,25 +0,0 @@ -MinGW - Licensing Terms - -Various pieces distributed with MinGW come with its own copyright and license: - -Basic MinGW runtime - MinGW base runtime package is uncopyrighted and placed in the public domain. - This basically means that you can do what you want with the code. - -w32api - You are free to use, modify and copy this package. - No restrictions are imposed on programs or object files compiled with this library. - You may not restrict the the usage of this library. - You may distribute this library as part of another package or as a modified package - if and only if you do not restrict the usage of the portions consisting - of this (optionally modified) library. - If distributed as a modified package then this file must be included. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty - of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -MinGW profiling code - MinGW profiling code is distributed under the GNU General Public License. - -The development tools such as GCC, GDB, GNU Make, etc all covered by GNU General Public License. diff --git a/build/windows/launcher/launch4j/w32api/crt2.o b/build/windows/launcher/launch4j/w32api/crt2.o deleted file mode 100755 index f81f836cf00..00000000000 Binary files a/build/windows/launcher/launch4j/w32api/crt2.o and /dev/null differ diff --git a/build/windows/launcher/launch4j/w32api/libadvapi32.a b/build/windows/launcher/launch4j/w32api/libadvapi32.a deleted file mode 100755 index c471853c7d0..00000000000 Binary files a/build/windows/launcher/launch4j/w32api/libadvapi32.a and /dev/null differ diff --git a/build/windows/launcher/launch4j/w32api/libgcc.a b/build/windows/launcher/launch4j/w32api/libgcc.a deleted file mode 100755 index d3f89479ee9..00000000000 Binary files a/build/windows/launcher/launch4j/w32api/libgcc.a and /dev/null differ diff --git a/build/windows/launcher/launch4j/w32api/libkernel32.a b/build/windows/launcher/launch4j/w32api/libkernel32.a deleted file mode 100755 index 5d3eb074f50..00000000000 Binary files a/build/windows/launcher/launch4j/w32api/libkernel32.a and /dev/null differ diff --git a/build/windows/launcher/launch4j/w32api/libmingw32.a b/build/windows/launcher/launch4j/w32api/libmingw32.a deleted file mode 100755 index d1f7888d812..00000000000 Binary files a/build/windows/launcher/launch4j/w32api/libmingw32.a and /dev/null differ diff --git a/build/windows/launcher/launch4j/w32api/libmsvcrt.a b/build/windows/launcher/launch4j/w32api/libmsvcrt.a deleted file mode 100755 index 6714146b695..00000000000 Binary files a/build/windows/launcher/launch4j/w32api/libmsvcrt.a and /dev/null differ diff --git a/build/windows/launcher/launch4j/w32api/libshell32.a b/build/windows/launcher/launch4j/w32api/libshell32.a deleted file mode 100755 index d35fbdaf375..00000000000 Binary files a/build/windows/launcher/launch4j/w32api/libshell32.a and /dev/null differ diff --git a/build/windows/launcher/launch4j/w32api/libuser32.a b/build/windows/launcher/launch4j/w32api/libuser32.a deleted file mode 100755 index 387fb650d23..00000000000 Binary files a/build/windows/launcher/launch4j/w32api/libuser32.a and /dev/null differ diff --git a/build/windows/launcher/launch4j/web/bullet.gif b/build/windows/launcher/launch4j/web/bullet.gif deleted file mode 100755 index f3f133bb872..00000000000 Binary files a/build/windows/launcher/launch4j/web/bullet.gif and /dev/null differ diff --git a/build/windows/launcher/launch4j/web/changelog.html b/build/windows/launcher/launch4j/web/changelog.html deleted file mode 100755 index 83511a55489..00000000000 --- a/build/windows/launcher/launch4j/web/changelog.html +++ /dev/null @@ -1,356 +0,0 @@ - - - - Launch4j - Cross-platform Java executable wrapper - - - - - - - -
-
- launch4j 3.0.1 -
- -
-

Changelog

- -

Changes in version 3.0.1 (20-07-2008)

-
    -
  • Enhanced the runtime logging (--l4j-debug).
  • -
  • Fixed critical bug #1925387 64-bit JDK detection problem caused a runtime search error (found by Stivo).
  • -
  • Fixed bug #1919406, #1989479 Not every option is loaded from saved xml file (found by Robert Lachner, Jan-Philipp Rathje).
  • -
  • Fixed bug #1930222 Simple typo (found by Daniel).
  • -
- -

Changes in version 3.0.0 (16-03-2008)

-
    -
  • FR #1390075 Added dynamic initial/max heap values.
  • -
  • FR #1707827 Allow to prefer JDK private runtimes over JREs (Ian Roberts).
  • -
  • FR #1730245 Allow to run only a single aplication instance (Sylvain Mina).
  • -
  • FR #1391610 Added IBM JRE/JDK support.
  • -
  • Added environment variable expansion in bundled JRE path.
  • -
  • Fixed critical bug #1882524 JRE detection problem on 64-bit Windows.
  • -
  • Fixed bug #1758912 Vista elevation to full administrator privileges.
  • -
  • Fixed bug #1784341 Problems with spaces in paths under linux (Michael Piefel).
  • -
  • Fixed bug where /bin was appended to path environment variable instead of jre_path/bin.
  • -
- -

Changed license to BSD, MIT (26-01-2008)

-
    -
  • - The upcoming Launch4j 3.0.0 release will be licensed under the much more - liberal new BSD license. The head subproject (the binary header attached to wrapped jars) - will be licensed under the similar MIT license. -
  • -
- -

Changes in version 3.0.0-pre2 (29-10-2006)

-
    -
  • Enhanced GUI.
  • -
  • Redesigned error reporting.
  • -
  • Added custom error messages.
  • -
  • Added support website feature.
  • -
  • Added PWD and OLDPWD special variables and access to the registry.
  • -
  • Runtime ini file extension changed to .l4j.ini, added comments (#).
  • -
  • FR #1427811 Initial process priority.
  • -
  • FR #1547339 Added VarFileInfo structure to Version Info (Stephan Laertz).
  • -
  • FR #1584295 Updated documentation for --l4j-debug. -
  • Fixed <jarArgs/> and <args/> config conversion bug (found by Dafe Simonek).
  • -
  • Fixed the Ant task exception reporting bug, added tmpdir and bindir attributes.
  • -
  • Fixed bug #1563415 Problem with launching application when ini file exists (found by mojomax).
  • -
  • Fixed bug #1527619 Console header wildcard expansion (found by erikjv).
  • -
  • Fixed bug #1544167 NPE when dontwrap and only classpath given (found by Hendrik Schreiber).
  • -
  • Fixed bug #1584264 Dropdown boxes get mixed up (found by Larsen).
  • -
- -

News (17-10-2006)

- - -

Changes in version 3.0.0-pre1 (21-07-2006)

-
    -
  • Improved configuration file format and embedded Ant config.
  • -
  • Launch executable jars, regular jars and class files.
  • -
  • Added dynamic classpath resolution with environment variable references and wildcards.
  • -
  • Added option to set environment variables before launching the application.
  • -
  • New command line switches to change the compiled options.
  • -
  • Improved debug information.
  • -
  • Added support for XP visual style manifests.
  • -
  • Added option to disable use of private JREs.
  • -
  • Many small fixes and improvements...
  • -
- -

Configuration file changes in 3.x

-
    -
  • Previous formats (1.x and 2.x) are supported.
  • -
  • <headerType> accepts gui|console
  • -
  • <jarArgs> was changed to <cmdLine>
  • -
  • - <launch4jConfig><headerObjects><file> was changed to - <launch4jConfig><obj> -
  • -
  • - <launch4jConfig><libs><file> was changed to - <launch4jConfig><lib> -
  • -
  • - <launch4jConfig><jre><args> was changed to multiple - <launch4jConfig><jre><opt> -
  • -
- -

Embedded Ant configuration changes in 3.x

-
    -
  • - <jre args="value"> was changed to - <jre><opt>value</opt></jre> -
  • -
  • Now it's possible to define headerObjects, libs and classpath.
  • -
- -

Changes in version 2.1.5 (21-07-2006)

-
    -
  • Changed the Java download site to http://java.com/download.
  • -
  • Now it's possible to use absolute and relative paths to specify the bundled JRE.
  • -
- -

Changes in version 2.1.4 (15-06-2006)

-
    -
  • - Fixed bug #1503996 Only the first wrapper instance had a custom process name - (found by Helge Böhme). -
  • -
- -

Changes in version 2.1.3 (31-05-2006)

-
    -
  • - Fixed bug #1497453 Ant task doesn't support relative jar path with '..' - (found by Aston, Pavel Moukhataev). -
  • -
  • Jar argument size limit is now 16KB.
  • -
  • Environment variable size limit raised to 32KB.
  • -
  • Allow to concatenate multiple env. variables in one property (Maria D.)
  • -
  • Added launch4j.tmpdir property.
  • -
- -

Changes in version 2.1.2 (03-04-2006)

-
    -
  • Important bugfix: insufficient command line buffer size was increased to 32KB - (found by Sebastian Kopsan).
  • -
  • Added runtime JVM options from an .ini file.
  • -
  • Launch4j's bin directory is now configurable through launch4j.bindir - system property.
  • -
- -

Changes in version 2.1.1 (25-01-2006)

-
    -
  • Fixed bug #1402748. Validation error occurred when using an Ant task with - embedded config and dontWrapJar option (found by Chris Nokleberg).
  • -
- -

Changes in version 2.1.0 (10-01-2006)

-
    -
  • More features and smaller header: 18 KB!!
  • -
  • Added launcher mode, you can choose whether or not to wrap the jar.
  • -
  • Spanish translation of the website/docs and program messages - (Patricio Martínez Ros).
  • -
  • JRE's bin directory is appended to the Path environment variable - (Ianiv Schweber).
  • -
  • Added special variables EXEDIR and EXEFILE that hold the executable's - directory and full path.
  • -
  • Support for mapping environment variables to system properties.
  • -
  • Added debug launching mode - various information is displayed before - starting the Java application.
  • -
  • Fixed min/max JRE version checking, previous versions allowed these - to be equal (found by Ryan).
  • -
  • Bug fixed. Quotes in jar/JVM arguments were handled incorrectly (found by Juan Alvarez Ferrando).
  • -
  • A few other enhancements.
  • -
- -

Changes in version 2.0.0 (31-10-2005)

-
    -
  • Launch4j for Mac OS X is available thanks to Peter Centgraf.
  • -
  • Added support for custom headers.
  • -
  • Fixed bug #1343908, command line arguments with spaces were handled - incorrectly by the console header (found by Oliver Schaefer / Steve Alberty).
  • -
  • Fixed stdin redirection bug (found by Timo Santasalo).
  • -
- -

Changes in version 2.0 RC3 (13-08-2005) - final RC

-
    -
  • Correct handling of pathnames with spaces.
  • -
  • Fixed the '%20' pathname bug.
  • -
  • Fixed basedir bug (Richard Xing).
  • -
  • Splash screen can be closed when the application window becomes visible - with out specifying it's title (Martin Busik). - Update your config file: <waitForTitle>title</waitForTitle> - is now <waitForWindow>true</waitForWindow>. -
  • -
  • Fixed build.bat files in demo directories.
  • -
- -

Changes in version 2.0 RC2 (21-06-2005)

-
    -
  • chdir allows to change the current directory to arbitrary paths - relative to the executable (FR #1144907). It's incompatible with - previous versions, update your config file: - <chdir>true</chdir> - is now <chdir>.</chdir>. -
  • -
  • Bundled JRE path no longer depends on chdir function.
  • -
  • Fixed Ant task bug, build files outside launch4j's directory - wouldn't work. Josh Elsasser submitted a patch that works without - setting launch4j's home dir in the build file. Thanks! -
  • -
  • Removed static edge from splash screen (Serge Baranov).
  • -
  • Program checks that the output file path doesn't contain spaces.
  • -
  • Fixed a NPE bug caused by a missing maxVersion property - (found by Morgan Schweers). -
  • -
  • Fixed relative JRE path bug (found by Nili_).
  • -
  • Cleaned up the Builder class.
  • -
  • Fixed Ant task NPE where the config was entirely defined in the - build file (Josh Elsasser). -
  • -
- -

Changes in version 2.0 RC (07-06-2005)

-
    -
  • Added an Ant task for better build integration.
  • -
  • Added 2.x documentation.
  • -
  • Updated the demo configuration files.
  • -
  • Fixed issues with relative paths in the configuration.
  • -
  • Removed the '-1' option in console mode.
  • -
  • Minor fixes.
  • -
- -

Changes in version 2.0 beta2 (23-05-2005)

-
    -
  • # comments are recognized when importing 1.x cfg files.
  • -
  • Added version information.
  • -
  • Resource file is displayed when a resource error occurs.
  • -
  • Fixed a bug found by Max, options on the first tab were always enabled.
  • -
- -

Changes in version 2.0 beta1 (13-05-2005)

-
    -
  • Completely new, cross-platform wrapper - create windows executables on Linux.
  • -
  • New .xml configuration file.
  • -
  • Application icon with multiple resolutions and color depths.
  • -
  • Swing GUI interface.
  • -
  • Header compiled with MinGW port of gcc instead of VC++.
  • -
- -

Changes in version 1.4.2 (12-03-2005)

-
    -
  • Fixed bug #1158143, stayAlive without a splash screen caused - an infinite loop (found by Gregory Kotsaftis). -
  • -
- -

Changes in version 1.4.1 (04-03-2005)

-
    -
  • Fixed bug #1119040, buffer for reading config properties - was too short (found by Tom Jensen and Neil). -
  • -
  • Added configurable splash timeout (FR #1102951).
  • -
  • Added option to disable the error message on splash timeout (FR #1109159).
  • -
  • Option to keep the gui launcher 'alive' after starting an application (FR #1124653).
  • -
  • Removed version info.
  • -
  • 'waitfor' property is now optional.
  • -
- -

Changes in version 1.4.0 (26-01-2005)

-
    -
  • Removed .lch4j suffix from process name, now it has the - form of the executable filename. The temporary launchers are stored in - launch4j-tmp directory (suggested by Emmanuel). -
  • -
  • Added support for console apps (FR #1050053).
  • -
- -

Changes in version 1.3.1 (05-11-2004)

-
    -
  • Fixed a bug where explorer window was opened instead of - launching the application when setProcName was set to false - (found by Rob Jones). -
  • -
  • Fixed temporary launcher deletion bug.
  • -
- -

Changes in version 1.3.0 (01-11-2004)

-
    -
  • Now you can configure launch4j to: -
      -
    • Use a bundled JRE.
    • -
    • Search for java, show an error message if the - right version cannot be found and open the java download page.
    • -
    • And a feature you asked for: use bundled JRE, if - that fails search for java and bring up the java download page on error.
    • -
    -
  • -
  • Enhanced code that sets the custom process name. In - case launch4j can't refresh the temporary launcher, bundled JRE on a - read only file system for example, it will use one created previously, - if it's present and has the correct size. If not, launching will still - continue, but with javaw.exe process name.Temporary launchers are - now created in the jre directory instead of jre/bin. -
  • -
  • errTitle property allows to set the title of the error message box.
  • -
- -

Changes in version 1.2.1 (25-09-2004)

-
    -
  • Bugfix that allows launching from command line using short - name (#1026514 / found by Zach Del) -
  • -
- -

Changes in version 1.2.0 (10-09-2004)

-
    -
  • Custom process name (myapp.lch4j.exe)
  • -
  • 9 KB stub!
  • -
  • Jar arguments
  • -
  • Bugfix that allows launching from command line.
  • -
  • Hide splash on javaw error.
  • -
  • Easier configuration with case insensitive parameters + show unrecognized parameter.
  • -
  • 12 KB demo application, 34 KB with splash screen.
  • -
  • Configuration parameter 'args' changed to 'jvmArgs'
  • -
-
- -
- - diff --git a/build/windows/launcher/launch4j/web/docs.html b/build/windows/launcher/launch4j/web/docs.html deleted file mode 100755 index 67f898eb27d..00000000000 --- a/build/windows/launcher/launch4j/web/docs.html +++ /dev/null @@ -1,585 +0,0 @@ - - - - Launch4j - Cross-platform Java executable wrapper - - - - - - - -
-
- launch4j 3.0.1 -
- -
-Running launch4j
-Configuration file
-Importing 1.x configuration
-Ant Task
-Additional JVM options at runtime
-Runtime options
-Settings
- -

Running launch4j

-Run launch4j.exe or launch4j script without command -line arguments to enter the GUI mode. - -
launch4j.exe
- -To wrap a jar in console mode use launch4jc.exe and -specify the configuration file. - -
launch4jc.exe config.xml
- -On Linux use the launch4j script. - -
launch4j ./demo/l4j/config.xml
- -

Configuration file

-Launch4j requires an xml configuration file for each output executable. -You can create and edit it conveniently using the graphic user -interface or your favorite editor. Alternatively it's possible to pass -all of the configuration parameters through the Ant task. All files -may be absolute paths or relative to the configuration file path. - -
-<!-- Bold elements are required -->
-<launch4jConfig>
-  <headerType>gui|console</headerType>
-  <outfile>file.exe</outfile>
-  <jar>file</jar>
-  <dontWrapJar>true|false</dontWrapJar>
-  <errTitle>text</errTitle>
-  <downloadUrl>http://java.com/download</downloadUrl>
-  <supportUrl>url</supportUrl>
-  <cmdLine>text</cmdLine>
-  <chdir>path</chdir>
-  <priority>normal|idle|high</priority>
-  <customProcName>true|false</customProcName>
-  <stayAlive>true|false</stayAlive>
-  <icon>file</icon>
-  <obj>header object file</obj>
-  ...
-  <lib>w32api lib</lib>
-  ...
-  <var>var=text</var>
-  ...
-  <classPath>
-    <mainClass>main class</mainClass>
-    <cp>classpath</cp>
-    ...
-  </classPath>
-  <singleInstance>
-    <mutexName>text</mutexName>
-    <windowTitle>text</windowTitle>
-  </singleInstance> 
-  <jre>
-    <!-- Specify one of the following or both -->
-    <path>bundled JRE path</path>
-    <minVersion>x.x.x[_xx]</minVersion>
-    <maxVersion>x.x.x[_xx]</maxVersion>
-    <jdkPreference>jreOnly|preferJre|preferJdk|jdkOnly</jdkPreference>
-    <!-- Heap sizes in MB and % of free memory -->
-    <initialHeapSize>MB</initialHeapSize>
-    <initialHeapPercent>%</initialHeapPercent>
-    <maxHeapSize>MB</maxHeapSize>
-    <maxHeapPercent>%</maxHeapPercent>
-    <opt>text</opt>
-    ...
-  </jre>
-  <splash>
-    <file>file</file>
-    <waitForWindow>true|false</waitForWindow>
-    <timeout>seconds [60]</timeout>
-    <timeoutErr>true|false</timeoutErr>
-  </splash>
-  <versionInfo>
-    <fileVersion>x.x.x.x</fileVersion>
-    <txtFileVersion>text</txtFileVersion>
-    <fileDescription>text</fileDescription>
-    <copyright>text</copyright>
-    <productVersion>x.x.x.x</productVersion>
-    <txtProductVersion>text</txtProductVersion>
-    <productName>text</productName>
-    <companyName>text</companyName>
-    <internalName>filename</internalName>
-    <originalFilename>filename.exe</originalFilename>
-  </versionInfo>
-  <messages>
-    <startupErr>text</startupErr>
-    <bundledJreErr>text</bundledJreErr>
-    <jreVersionErr>text</jreVersionErr>
-    <launcherErr>text</launcherErr>
-  </messages>
-</launch4jConfig>
-
- -
-
<headerType>
-
- Type of the header used to wrap the application. - - - - - - - - - - - - - - - - - - - - - - - -
Header typeLauncherSplash screenWait for the application to close
guijavawyeswrapper waits only if stayAlive is set to true, - otherwise it terminates immediately or after closing - the splash screen. -
consolejavanoalways waits and returns application's exit code.
-
-
-
-
<outfile>
-
Output executable file.
-
-
-
<jar>
-
- Optional, by default specifies the jar to wrap. To launch a jar without - wrapping it enter the runtime path of the jar relative to - the executable and set <dontWrapJar> to true. - For example, if the executable launcher and the application jar named - calc.exe and calc.jar are in the same directory - then you would use <jar>calc.jar</jar> - and <dontWrapJar>true</dontWrapJar>. -
-
-
-
<dontWrapJar>
-
- Optional, defaults to false. Launch4j by default wraps jars in native - executables, you can prevent this by setting <dontWrapJar> to true. - The exe acts then as a launcher and starts the application specified in - <jar> or <classPath><mainClass> -
-
-
-
<errTitle>
-
- Optional, sets the title of the error message box that's displayed if Java cannot - be found for instance. This usually should contain the name of your - application. The console header prefixes error messages with this - property (myapp: error...) -
-
-
-
<cmdLine>
-
Optional, constant command line arguments.
-
-
-
<chdir>
-
Optional. Change current directory to an arbitrary path relative to the executable. - If you omit this property or leave it blank it will have no effect. - Setting it to . will change the current dir to the same directory - as the executable. .. will change it to the parent directory, and so on. -
-
-
<chdir>.</chdir>
-
-
-
<chdir>../somedir</chdir>
-
-
-
-
<customProcName>
-
Optional, defaults to false. - Set the process name as the executable filename and use Xp style manifests - (if any). - Creates a temporary file in launch4j-tmp directory inside the used JRE. - These files are deleted by any launch4j wrapped application, which sets - the process name and uses the same JRE. The removal takes place - when the application starts, - so at least one copy of this file will always be present. -
-
-
-
<stayAlive>
-
Optional, defaults to false in GUI header, always true in console header. - When enabled the launcher waits for the Java application - to finish and returns it's exit code. -
-
-
-
<icon>
-
Application icon in ICO format. May contain multiple color depths/resolutions.
-
-
-
<obj>
-
Optional, custom headers only. Ordered list of header object files.
-
-
-
<lib>
-
Optional, custom headers only. Ordered list of libraries used by header.
-
-
-
<singleInstance>
-
Optional, allow to run only a single instance of the application.
-
-
-
-
<mutexName>
-
Unique mutex name that will identify the application.
-
<windowTitle>
-
Optional, recognized by GUI header only. Title or title part of a window - to bring up instead of running a new instance. -
-
-
-
-
<jre>
-
Required element that groups JRE settings.
-
-
-
-
<path>, <minVersion>, <maxVersion>
-
The <path> property is used - to specify the absolute or relative path (to the executable) of a bundled JRE, it - does not rely on the current directory or <chdir>. - Note that this path is not checked until the actual application execution. - If you'd like the wrapper to search for a JRE (public or SDK private) - use the <minVersion> property, you may also specify - the <maxVersion> to prevent it from using higher Java versions. - Launch4j will always use the highest version available (in the min/max range of course). - If a Sun's JRE is not available or does not satisfy the search criteria, - the search will be repeated on IBM runtimes. - You can also combine these properties to change the startup process... -
-
-
-
-
<path>
-
Run if bundled JRE and javaw.exe are present, otherwise stop with error.
-
<path> + <minVersion>  [+ <maxVersion>]
-
Use bundled JRE first, if it cannot be located search for Java, - if that fails display error message and open the Java download page. -
-
<minVersion>  [+ <maxVersion>]
-
Search for Java, if an appropriate version cannot be found display - error message and open the Java download page. -
-
-
-
-
-
-
<jdkPreference>
-
Optional, defaults to preferJre; Allows you to specify a preference - for a public JRE or a private JDK runtime. Valid values are: -
-
-
-
-
jreOnly
-
Always use a public JRE (equivalent to the - old option dontUsePrivateJres=true)
-
preferJre
-
Prefer a public JRE, but use a JDK private - runtime if it is newer than the public - JRE (equivalent to the old option - dontUsePrivateJres=false)
-
preferJdk
-
Prefer a JDK private runtime, but use a - public JRE if it is newer than the - JDK
-
jdkOnly
-
Always use a private JDK runtime (fails - if there is no JDK installed)
-
-
-
-
HeapSize, HeapPercent
-
If size and percent are specified, then the setting which yields - more memory will be chosen at runtime. In other words, setting both values - means: percent of free memory no less than size in MB. -
-
-
-
-
<initialHeapSize>
-
Optional, initial heap size in MB.
-
-
-
<initialHeapPercent>
-
Optional, initial heap size in % of free memory.
-
-
-
<maxHeapSize>
-
Optional, max heap size in MB.
-
-
-
<maxHeapPercent>
-
Optional, max heap size in % of free memory.
-
-
-
-
<opt>
-
Optional, accepts everything you would normally pass to - java/javaw launcher: assertion options, system properties and X options. - Here you can map environment and special variables EXEDIR - (exe's runtime directory), EXEFILE (exe's runtime full file path) - to system properties. All variable references must be surrounded with - percentage signs and quoted. -
-<opt>-Dlaunch4j.exedir="%EXEDIR%"</opt>
-<opt>-Dlaunch4j.exefile="%EXEFILE%"</opt>
-<opt>-Denv.path="%Path%"</opt>
-<opt>-Dsettings="%HomeDrive%%HomePath%\\settings.ini"</opt>
-
-
-
-
- -
-
<splash>
-
Optional, groups the splash screen settings. Allowed only in GUI header.
-
-
-
-
<file>
-
Splash screen image in BMP format.
-
-
-
<waitForWindow>
-
Optional, defaults to true. Close the splash screen when an application - window or Java error message box appears. If set to false, - the splash screen will be closed on timeout. -
-
-
-
<timeout>
-
Optional, defaults to 60. Number of seconds after which the splash screen - must be closed. Splash timeout may cause an error depending on - <timeoutErr>. -
-
-
-
<timeoutErr>
-
Optional, defaults to true. True signals an error on splash timeout, - false closes the splash screen quietly. -
-
-
- -
-
<versionInfo>
-
Optional, version information to be displayed by the Windows Explorer.
-
-
-
-
<fileVersion>
-
Version number 'x.x.x.x'
-
-
-
<txtFileVersion>
-
Free form file version, for example '1.20.RC1'.
-
-
-
<fileDescription>
-
File description presented to the user.
-
-
-
<copyright>
-
Legal copyright.
-
-
-
<productVersion>
-
Version number 'x.x.x.x'
-
-
-
<txtProductVersion>
-
Free form file version, for example '1.20.RC1'.
-
-
-
<productName>
-
Text.
-
-
-
<companyName>
-
Optional text.
-
-
-
<internalName>
-
Internal name without extension, original filename or module name for example.
-
-
-
<originalFilename>
-
Original name of the file without the path. Allows to determine - whether a file has been renamed by a user. -
-
-
- -

Importing 1.x configuration

-It's possible to import a 1.x configuration file using the GUI -interface. Open the file, correct the paths and save it as a new xml -configuration. - -

Ant task

-You may set a launch4j directory property or change the task definition. - -
<property name="launch4j.dir" location="/opt/launch4j" />
- -Define the task in your Ant build script. - -
-<taskdef name="launch4j"
-    classname="net.sf.launch4j.ant.Launch4jTask"
-    classpath="${launch4j.dir}/launch4j.jar
-        :${launch4j.dir}/lib/xstream.jar" />
-
- -Execute the task! - -
<launch4j configFile="./l4j/demo.xml" />
- -You can set or override the following configuration properties... -

- jar="absolute path or relative to basedir"
- jarPath="relative path"
- outfile
- fileVersion
- txtFileVersion
- productVersion
- txtProductVersion
- bindir="alternate bin directory..."
- tmpdir="alternate working directory..." -

- -
-<launch4j configFile="./l4j/demo.xml" outfile="mydemo.exe"
-    fileVersion="1.0.0.0" txtFileVersion="1.0 RC2" />
-
- -You can also define the entire configuration in the task, but it will -not be possible to edit such a file in the GUI mode. All paths except -for <chdir>, <jre><path> and jarPath -are calculated using the basedir project attribute. - -
-<launch4j>
-  <config headerType="gui" outfile="demo.exe"
-      dontWrapJar="true" jarPath="demo.jar" >
-    <var>SETTINGS="%HomeDrive%%HomePath%\\settings.ini"</var>
-    <classPath mainClass="org.demo.DemoApp">
-        <cp>./lib/looks.jar</cp>
-        <cp>%USER_LIBS%/*.jar</cp>
-    </classPath>
-    <jre minVersion="1.4.0">
-        <opt>-Dlaunch4j.exedir="%EXEDIR%"</opt>
-        <opt>-Dlaunch4j.exefile="%EXEFILE%"</opt>
-    </jre>
-  </config>
-</launch4j>
-
- -

Additional JVM options at runtime

-When you create a wrapper or launcher all configuration details are compiled into the -executable and cannot be changed without recreating it or hacking with a resource editor. -Launch4j 2.1.2 introduces a new feature that allows to pass additional JVM options -at runtime from an .l4j.ini file. Now you can specify the options in the configuration file, -ini file or in both, but you cannot override them. The ini file's name must correspond -to the executable's (myapp.exe : myapp.l4j.ini). -The arguments should be separated with spaces or new lines, environment variable -expansion is supported, for example: -
-# Launch4j runtime config
--Dswing.aatext=true
--Dsomevar="%SOMEVAR%"
--Xms16m
-
- -

Runtime options

-
-
--l4j-debug
-
- To make sure the output executable is configured correctly you can use the - debug launching mode to log various information to the launch4j.log file. -
- -
--l4j-default-proc
-
- Use default process name. -
- -
--l4j-dont-wait
-
- Disable the "stay alive" function. -
- -
--l4j-no-splash
-
- Disable the splash screen. -
- -
--l4j-no-splash-err
-
- Disable splash screen error on timeout, might be useful on very slow computers. -
-
- -

Settings

-
-
Alternate bin directory: launch4j.bindir
-
- It's possible to override the default bin directory location which contains windres and ld - tools using the launch4j.bindir system property. The property can have two forms: - a path relative to Launch4j's directory (altbin for example) or an absolute path. -
- -
Working directory: launch4j.tmpdir
-
Change the working directory if the default path contains spaces which windres cannot handle.
-
-
- -
- - diff --git a/build/windows/launcher/launch4j/web/index.html b/build/windows/launcher/launch4j/web/index.html deleted file mode 100755 index d1f928e6ec4..00000000000 --- a/build/windows/launcher/launch4j/web/index.html +++ /dev/null @@ -1,128 +0,0 @@ - - - - Launch4j - Cross-platform Java executable wrapper - - - - - - - -
-
- launch4j 3.0.1 -
- -
-

Cross-platform Java executable wrapper

-

- Launch4j is a cross-platform tool for wrapping - Java applications distributed as jars in lightweight Windows - native executables. The executable can be - configured to search for a certain JRE version or - use a bundled one, and it's possible to set - runtime options, like the initial/max heap size. - The wrapper also provides better user experience - through an application icon, a native pre-JRE - splash screen, a custom process name, and a Java - download page in case the appropriate JRE cannot - be found. -

-How to use Launch4 -

Features

-
    -
  • Launch4j wraps jars in Windows native executables and allows to run them - like a regular Windows program. It's possible to wrap applications - on Windows, Linux, Mac OS X and Solaris! -
  • -
  • Also creates launchers for jars and class files without wrapping.
  • -
  • - Supports executable jars and dynamic classpath resolution using - environment variables and wildcards. -
  • -
  • Doesn't extract the jar from the executable.
  • -
  • Custom application icon with multiple resolutions and color depths.
  • -
  • Native pre-JRE splash screen in BMP format shown until - the Java application starts. -
  • -
  • Process name as the executable filename to easily - identify your application, initial priority and - single aplication instance features. -
  • -
  • Works with a bundled JRE or searches for newest Sun or IBM JRE / JDK in given - version range.
  • -
  • Opens Java download page if an appropriate Java version cannot be - found or a support website in case of an error. -
  • -
  • Supports GUI and console apps.
  • -
  • Supports Vista manifests and XP visual style manifests.
  • -
  • Passes command line arguments, also supports constant arguments.
  • -
  • Allows to set the initial/max heap size also dynamically in percent of free memory.
  • -
  • JVM options: set system properties, tweak the garbage collection...
  • -
  • Runtime JVM options from an .l4j.ini file.
  • -
  • Runtime command line switches to change the compiled options.
  • -
  • Access to environment variables, the registry and executable file path through system properties.
  • -
  • Set environment variables.
  • -
  • Option to change current directory to the executable location.
  • -
  • The JRE's bin directory is appended to the Path environment variable.
  • -
  • Custom version information shown by Windows Explorer.
  • -
  • GUI and command line interface.
  • -
  • Build integration through an Ant task and a Maven Plugin.
  • -
  • Lightweight: 26 KB!
  • -
  • It's free and may be used for commercial purposes.
  • -
  • Includes a sample application and Ant script - that automates the build process from Java sources to native executable. -
  • -
  • The wrapped program works on all Windows platforms (98/Me/NT/2K/XP/Vista), - Launch4j works on NT/2K/XP/Vista, Linux, Mac OS X (build on 10.4) and Sparc Solaris 8-10. -
  • -
-

License

-

- This program is free software licensed under the - BSD license, the head subproject - (the code which is attached to the wrapped jars) is licensed under the - MIT license. - Launch4j may be used for wrapping closed source, commercial applications. -

-

Info

-

- Running Launch4j on other Java enabled platforms is a matter of getting a binary version - of MinGW binutils 2.15.90 (windres and ld only) - for your system or compiling them. If you'll provide these, I'll be able to create a binary package - available for download. -

- -
- -
- - diff --git a/build/windows/launcher/launch4j/web/launch4j-use.gif b/build/windows/launcher/launch4j/web/launch4j-use.gif deleted file mode 100755 index ccb888247ea..00000000000 Binary files a/build/windows/launcher/launch4j/web/launch4j-use.gif and /dev/null differ diff --git a/build/windows/launcher/launch4j/web/launch4j.gif b/build/windows/launcher/launch4j/web/launch4j.gif deleted file mode 100755 index 27552074ac3..00000000000 Binary files a/build/windows/launcher/launch4j/web/launch4j.gif and /dev/null differ diff --git a/build/windows/launcher/launch4j/web/links.html b/build/windows/launcher/launch4j/web/links.html deleted file mode 100755 index 4213b86f9d6..00000000000 --- a/build/windows/launcher/launch4j/web/links.html +++ /dev/null @@ -1,73 +0,0 @@ - - - - Launch4j - Cross-platform Java executable wrapper - - - - - - - - - - diff --git a/build/windows/launcher/launch4j/web/style.css b/build/windows/launcher/launch4j/web/style.css deleted file mode 100755 index f57c086d684..00000000000 --- a/build/windows/launcher/launch4j/web/style.css +++ /dev/null @@ -1,159 +0,0 @@ -body, table { - font: 12px/20px Verdana, Arial, Helvetica, sans-serif; -} - - -pre { - padding: 8px; - border: 1px dashed #999999; - background-color: #f1f1f1; - font: 13px/20px "Courier New", Courier, monospace; -} - - -.version { - color: #307fe1; - font-weight: bold; -} - - -.codeword { - color: #3333ff; -} -.attrib { - color: #404040; -} -.option { - font-family: "Courier New", Courier, monospace; - font-weight: bold; -} - - -dt { - margin-top: 1.5em; - color: #404040; - font-size: 115%; - border-bottom: 1px solid #cccccc; -} -dd { - margin-left: 1em; -} - - -.warn, ul.changes em { - color: #ff0000; -} - - -table { - margin-top: 1em; - padding: 0; - border: 1px solid #999999; - border-collapse: collapse; - text-align: center; -} -table th { - padding: 2px 4px; - border: 1px solid #999999; - background-color: #f1f1f1; -} -table td { - padding: 2px 4px; - border: 1px solid #999999; -} -.description { - text-align: left; -} - - -#container { - width: 90%; - margin: 10px auto; - border-width: 0; - background-color: #ffffff; -} - - -#top { - padding: 0.5em; - background-color: #ffffff; -} -#top h1 { - margin: 0; - padding: 0; -} - - -#leftnav { - float: left; - width: 170px; - margin: 0; - padding: 0.5em; - background-color: #ffffff; -} -#leftnav ul { - margin: 0; - padding: 0; - border: none; - list-style-type: none; - font-size: 115%; -} -#leftnav a { - width: 170px; - height: 1.6em; - line-height: 1.6em; - display: block; - padding-left: 0.2em; -} -#leftnav a:link, #leftnav a:visited { - text-decoration: none; - color: #666666; -} -#leftnav a:hover { - background-color: #307fe1; - color: #ffffff; -} - - -#content { - max-width: 52em; - margin-left: 190px; - padding: 1em; - border-left: 1px solid #cccccc; - background-color: #ffffff; -} - -#content ul { - list-style-image: url('bullet.gif'); -} - -#content a:link { - text-decoration: none; - color: #307fe1; -} -#content a:visited { - text-decoration: none; - color: #307fe1; -} -#content a:hover { - color: #307fe1; - text-decoration: underline; -} - -#content h2 { - font-size: 150%; -} -#content h2:first-child { - margin: 0 0 0.5em; -} - - -.footer { - clear: both; - margin: 0; - padding: 0.5em; - background-color: #ffffff; - color: #333333; - text-align: center; - font-size: 90%; -} diff --git a/hardware/arduino/boards.txt b/hardware/arduino/boards.txt index 145d551c095..fc29ee4f9db 100644 --- a/hardware/arduino/boards.txt +++ b/hardware/arduino/boards.txt @@ -265,7 +265,7 @@ ethernet.bootloader.file=optiboot_atmega328.hex ethernet.bootloader.unlock_bits=0x3F ethernet.bootloader.lock_bits=0x0F -ethernet.build.variant=standard +ethernet.build.variant=ethernet ethernet.build.mcu=atmega328p ethernet.build.f_cpu=16000000L ethernet.build.core=arduino @@ -522,3 +522,46 @@ atmega8.build.mcu=atmega8 atmega8.build.f_cpu=16000000L atmega8.build.core=arduino atmega8.build.variant=standard + +############################################################## + +robotControl.name=Arduino Robot Control +robotControl.upload.protocol=avr109 +robotControl.upload.maximum_size=28672 +robotControl.upload.speed=57600 +robotControl.upload.disable_flushing=true +robotControl.bootloader.low_fuses=0xff +robotControl.bootloader.high_fuses=0xd8 +robotControl.bootloader.extended_fuses=0xcb +robotControl.bootloader.path=caterina-Arduino_Robot +robotControl.bootloader.file=Caterina-Robot-Control.hex +robotControl.bootloader.unlock_bits=0x3F +robotControl.bootloader.lock_bits=0x2F +robotControl.build.mcu=atmega32u4 +robotControl.build.f_cpu=16000000L +robotControl.build.vid=0x2341 +robotControl.build.pid=0x8038 +robotControl.build.core=robot +robotControl.build.variant=robot_control + +############################################################## + +robotMotor.name=Arduino Robot Motor +robotMotor.upload.protocol=avr109 +robotMotor.upload.maximum_size=28672 +robotMotor.upload.speed=57600 +robotMotor.upload.disable_flushing=true +robotMotor.bootloader.low_fuses=0xff +robotMotor.bootloader.high_fuses=0xd8 +robotMotor.bootloader.extended_fuses=0xcb +robotMotor.bootloader.path=caterina-Arduino_Robot +robotMotor.bootloader.file=Caterina-Robot-Motor.hex +robotMotor.bootloader.unlock_bits=0x3F +robotMotor.bootloader.lock_bits=0x2F +robotMotor.build.mcu=atmega32u4 +robotMotor.build.f_cpu=16000000L +robotMotor.build.vid=0x2341 +robotMotor.build.pid=0x8039 +robotMotor.build.core=robot +robotMotor.build.variant=robot_motor + diff --git a/hardware/arduino/bootloaders/atmega/ATmegaBOOT_168.c b/hardware/arduino/bootloaders/atmega/ATmegaBOOT_168.c index 2b9fefa2633..880cf9b41f2 100755 --- a/hardware/arduino/bootloaders/atmega/ATmegaBOOT_168.c +++ b/hardware/arduino/bootloaders/atmega/ATmegaBOOT_168.c @@ -950,10 +950,10 @@ char getch(void) count++; if (count > MAX_TIME_COUNT) app_start(); - } - - return UDR0; } + + return UDR0; + } else if(bootuart == 2) { while(!(UCSR1A & _BV(RXC1))) { /* 20060803 DojoCorp:: Addon coming from the previous Bootloader*/ diff --git a/hardware/arduino/bootloaders/caterina-Arduino_Robot/Caterina-Robot-Control.hex b/hardware/arduino/bootloaders/caterina-Arduino_Robot/Caterina-Robot-Control.hex new file mode 100644 index 00000000000..bc13bbb44aa --- /dev/null +++ b/hardware/arduino/bootloaders/caterina-Arduino_Robot/Caterina-Robot-Control.hex @@ -0,0 +1,258 @@ +:1070000055C000006EC000006CC000006AC00000E7 +:1070100068C0000066C0000064C0000062C00000DC +:1070200060C000005EC00000FCC400005AC0000048 +:1070300058C0000056C0000054C0000052C00000FC +:1070400050C000005DC000004CC000004AC00000FD +:1070500048C0000046C0000044C0000042C000001C +:1070600040C000003EC000003CC000003AC000002C +:1070700038C0000036C0000034C0000032C000003C +:1070800030C000002EC000002CC000002AC000004C +:1070900028C0000026C0000024C0000022C000005C +:1070A00020C000001EC000001CC0000011241FBE34 +:1070B000CFEFDAE0DEBFCDBF11E0A0E0B1E0E6E463 +:1070C000FFE702C005900D92AC3AB107D9F711E085 +:1070D000ACEAB1E001C01D92A53CB107E1F74FD386 +:1070E00030C78ECFF89410926F001092810081E02B +:1070F00085BF15BE47985D9A289A0C9400000895A4 +:107100001F920F920FB60F9211242F938F939F937C +:10711000EF93FF9310928500109284008091AC0150 +:107120009091AD01009741F001979093AD0180934C +:10713000AC01892B09F45D9A8091AE019091AF0169 +:10714000009741F001979093AF018093AE01892B96 +:1071500009F4289A8091B2019091B301019690931D +:10716000B3018093B201E0E0F0E0859194918F5FEC +:107170009F4F49F08091B0019091B1010196909399 +:10718000B1018093B001FF91EF919F918F912F9169 +:107190000F900FBE0F901F90189584E08093E90028 +:1071A0000DC08091E8008B778093E80003C08EB318 +:1071B000882351F08091E80082FFF9CF8091E800A8 +:1071C00085FFEFCF8091F1000895982F83E08093A1 +:1071D000E9008091E80085FD0DC08091E8008E7780 +:1071E0008093E80003C08EB3882369F08091E800A3 +:1071F00080FFF9CF9093F1005D9884E690E0909342 +:10720000AD018093AC0108954F925F926F927F928F +:107210008F929F92AF92BF92CF92DF92EF92FF92A6 +:107220000F931F93CF93DF9384E08093E9008091C5 +:10723000E80082FF57C2289884E690E09093AF015F +:107240008093AE01AADF182F853481F48CE49DE190 +:107250009093B1018093B00107B600FCFDCFF9997E +:10726000FECF81E180935700E89503C0843519F47F +:1072700094DF8DE00DC28C34E1F38035D1F3843797 +:1072800021F484E4A2DF80E003C2813611F489E5B1 +:10729000FFC18134B1F481DF182F7FDF90E0880FC8 +:1072A000991FAA2797FDA095BA2F312F330F20E001 +:1072B000442737FD4095542F822B932BA42BB52BBD +:1072C000B8C1803711F483E5E3C1833549F4C0E0E8 +:1072D000D1E089917ADF21E0C730D207D1F7D9C157 +:1072E000863521F481E371DF80E3D2C1833731F445 +:1072F00087E86BDF85E969DF8EE1CAC18536B9F4BD +:10730000E0E0F0E093E085E090935700E89507B661 +:1073100000FCFDCF80935700E89507B600FCFDCF39 +:10732000E058FF4FA0E7E030FA0771F7A2CF8237AD +:1073300039F4E1E0F0E089E0809357008491A8C13E +:10734000863439F4E0E0F0E089E0809357008491DE +:107350009FC18E3439F4E3E0F0E089E08093570078 +:10736000849196C1813539F4E2E0F0E089E08093C0 +:10737000570084918DC1823631F489E526DF80E0A3 +:1073800024DF80E885C1823419F0873609F0E5C032 +:107390001092B1011092B00100DF082FFEDEF82E2E +:1073A000FCDE682E8554823008F071C1902F80E099 +:1073B000CF2DD0E0C82BD92B10926F00173609F0D3 +:1073C0004BC081E180935700E895DD24CC24C39421 +:1073D0003FC0E090B501F090B6010091B701109167 +:1073E000B801B6E46B16D9F4ED2DF0E0EE29FF29D3 +:1073F000E4918E2FEADEDD2081F082E090E0A0E0D3 +:10740000B0E0E80EF91E0A1F1B1FE092B501F092D2 +:10741000B6010093B7011093B801DC2418C0D8015D +:10742000C701B695A7959795879575D5CEDE82E06D +:1074300090E0A0E0B0E0E80EF91E0A1F1B1FE092EA +:10744000B501F092B6010093B7011093B8012197EE +:10745000209709F0BECF7DC08090B5019090B60115 +:10746000A090B701B090B80196E4691609F05DC02C +:1074700083E0F40180935700E89507B600FCFDCF48 +:1074800054C0F6E46F1661F5772031F1E090B50154 +:10749000F090B6010091B7011091B8017EDED82EB0 +:1074A000CC24852D90E08C299D29F7010C01409278 +:1074B0005700E895112482E090E0A0E0B0E0E80EEB +:1074C000F91E0A1F1B1FE092B501F092B60100934E +:1074D000B7011093B80102C060DE582E742423C097 +:1074E000E090B501F090B6010091B7011091B8019C +:1074F00016950795F794E79450DE682FC70113D5CA +:107500008091B5019091B601A091B701B091B801F9 +:107510000296A11DB11D8093B5019093B601A09371 +:10752000B701B093B801219704C0552477244424AF +:107530004394209709F0A5CF96E4691641F485E0BD +:10754000F40180935700E89507B600FCFDCF8DE06D +:107550003CDE82E080936F009CC0833471F4009124 +:10756000B5011091B60119DE90E021E0F8010C019F +:1075700020935700E89511247CCE833619F5E090CE +:10758000B501F090B6010091B7011091B80105DE88 +:10759000F701E16090E021E00C0120935700E895AD +:1075A000112482E090E0A0E0B0E0E80EF91E0A1F8E +:1075B0001B1FE092B501F092B6010093B701109342 +:1075C000B80157CE8D3661F4E091B501F091B60166 +:1075D00085E080935700E89507B600FCFDCF49CEC3 +:1075E000823551F4E091B501F091B6010591149105 +:1075F000812FEBDD802F4CC0843421F5E090B50164 +:10760000F090B6010091B7011091B8011695079559 +:10761000F794E794C2DD682FC70185D48091B50146 +:107620009091B601A091B701B091B8010296A11D49 +:10763000B11D8093B5019093B601A093B701B093AB +:10764000B80117CE843609F5E090B501F090B60187 +:107650000091B7011091B801D801C701B695A7955F +:107660009795879558D4B1DD82E090E0A0E0B0E036 +:10767000E80EF91E0A1F1B1FE092B501F092B60139 +:107680000093B7011093B80104C08B3111F08FE360 +:107690009CDD83E08093E9009091E8008091E80010 +:1076A0008E778093E80095FF04C010C08EB38823C6 +:1076B000C9F08091E80080FFF9CF8091E8008E77D3 +:1076C0008093E80003C08EB3882361F08091E800C6 +:1076D00080FFF9CF84E08093E9008091E8008B7708 +:1076E0008093E800DF91CF911F910F91FF90EF9071 +:1076F000DF90CF90BF90AF909F908F907F906F90D2 +:107700005F904F9008959091BD01892F8F778132BE +:1077100049F58091BE018032A1F0813219F5913A8C +:1077200009F58091E800877F8093E8008CE091E084 +:1077300067E070E027D28091E8008B778093E800C3 +:107740000895913279F48091E800877F8093E80072 +:107750008CE091E067E070E079D28091E8008E776C +:107760008093E800089582E061EC42E0D1D083E0AC +:1077700061E842E1CDD084E060E842E1C9C01F93F6 +:10778000209100081092000844B714BE88E10FB69B +:10779000F89480936000109260000FBE80E8E0E0F3 +:1077A000F0E00FB6F89480936100E09361000FBEA3 +:1077B00031E035BF92E095BF3F9A209A559A809369 +:1077C00061001092610047985D9A289A1092890092 +:1077D0008AEF8093880090936F0083E0809381000C +:1077E000859194918F5F9F4F11F03093B401942F46 +:1077F00041FF19C0809109012817A9F08093000862 +:10780000789480911301882339F08091B20190918E +:10781000B3018F5E9240C8F310920008F89481E0A3 +:10782000809313010CC090FF04C08091B4018823A1 +:1078300051F493FF09C080910901281729F0809124 +:10784000B401882309F04EDCD4D078941092B101B1 +:107850001092B0011EEF20C0D7DC4BD38091B00155 +:107860009091B10181549F4110F0109213018091C9 +:10787000B9019091BA0101969093BA018093B90130 +:10788000292F97FF03C0512F591B252F220F28178F +:1078900010F4479801C0479A809113018823E1F6BC +:1078A0008091E00081608093E0001CDC80E090E04B +:1078B0001F910895FA01923049F0933061F09130B0 +:1078C000F9F484E191E022E130E01EC086E291E02B +:1078D0002EE330E019C0882329F484E691E024E007 +:1078E00030E012C0813029F488E691E028E230E0EF +:1078F0000BC0823029F482E991E028E130E004C035 +:1079000080E090E020E030E091838083C901089519 +:107910008093E9008091EB0081608093EB001092EE +:10792000ED006093EC004093ED008091EE00881F25 +:107930008827881F08958091BD0188238CF403C097 +:107940008EB38823B1F08091E80082FFF9CF809157 +:10795000E8008B778093E80008958EB3882349F080 +:107960008091E80080FFF9CF8091E8008E778093C6 +:10797000E8000895EF92FF920F931F9345D04CD0EB +:1079800008ED10E0F80180818F7780838081806826 +:10799000808380818F7D808319BC1EBA1092BB01C9 +:1079A00080EEE82EF12CF70180818B7F8083F80137 +:1079B00080818160808380E060E042E0A9DFE1EEC9 +:1079C000F0E080818E7F8083E2EEF0E08081816054 +:1079D0008083808188608083F70180818E7F8083AF +:1079E000F8018081806180831F910F91FF90EF905B +:1079F0000895E7EDF0E08081816080838AE482BFB2 +:107A000081E08093BC01B6CFE8EDF0E080818E7F0D +:107A100080831092E20008951092DA001092E10043 +:107A200008951F920F920FB60F9211242F933F9338 +:107A30004F935F936F937F938F939F93AF93BF9376 +:107A4000EF93FF938091DA0080FF1BC08091D800F4 +:107A500080FF17C08091DA008E7F8093DA008091DA +:107A6000D90080FF0BC080E189BD82E189BD09B4E6 +:107A700000FEFDCF81E08EBB3BD203C019BC1EBA15 +:107A800037D28091E10080FF17C08091E20080FF33 +:107A900013C08091E2008E7F8093E2008091E2002B +:107AA00080618093E2008091D80080628093D8004A +:107AB00019BC85E08EBB1CD28091E10084FF2CC0F4 +:107AC0008091E20084FF28C080E189BD82E189BD08 +:107AD00009B400FEFDCF8091D8008F7D8093D8003F +:107AE0008091E1008F7E8093E1008091E2008F7EA3 +:107AF0008093E2008091E20081608093E2008091B7 +:107B0000BB01882331F48091E30087FD02C081E04E +:107B100001C084E08EBBECD18091E10083FF21C0E5 +:107B20008091E20083FF1DC08091E100877F8093F8 +:107B3000E10082E08EBB1092BB018091E1008E7F5C +:107B40008093E1008091E2008E7F8093E20080913B +:107B5000E20080618093E20080E060E042E0D8DEF5 +:107B6000C7D1FF91EF91BF91AF919F918F917F917D +:107B70006F915F914F913F912F910F900FBE0F909A +:107B80001F9018959C014091C3015091C401461764 +:107B9000570718F4F90190E044C06115710511F020 +:107BA000AB01F8CF8091E8008E778093E80040E049 +:107BB00050E0F0CF8EB3882309F444C0853009F437 +:107BC00043C08091E80083FF02C081E00895809166 +:107BD000E80082FD31C08091E80080FF22C08091E2 +:107BE000F3009091F200782F60E0292F30E0262BEF +:107BF000372B07C081918093F100415050402F5F97 +:107C00003F4F4115510519F02830310598F390E0A8 +:107C10002830310509F491E08091E8008E77809357 +:107C2000E8004115510531F6992321F605C08EB3C0 +:107C3000882341F0853041F08091E80082FFF7CF42 +:107C400080E0089582E0089583E008959C01611525 +:107C5000710529F48091E8008B778093E800F901A1 +:107C600026C08EB3882391F1853091F18091E80090 +:107C700083FF02C081E008958091E80082FFF1CF88 +:107C800006C08091F10081936150704059F02091BD +:107C9000F3008091F200322F20E090E0822B932BB2 +:107CA000892B79F78091E8008B778093E800611544 +:107CB0007105B9F605C08EB3882341F0853041F0D7 +:107CC0008091E80080FFF7CF80E0089582E008957A +:107CD00083E008950F931F93DF93CF9300D0CDB728 +:107CE000DEB7EDEBF1E08091F100819381E0E53CBE +:107CF000F807C9F708DD8091E80083FFE4C08091B0 +:107D0000BD019091BE01953009F46DC0963040F4EC +:107D1000913081F1913070F0933009F0D4C02AC0D5 +:107D2000983009F4A3C0993009F4B2C0963009F034 +:107D3000CAC07CC0803809F4C6C0823809F0C3C00C +:107D40008091C10187708093E9008091EB001092CF +:107D5000E9002091E800277F2093E80090E025E0EB +:107D6000969587952A95E1F781708093F10010929E +:107D7000F10087C0882319F0823009F0A4C08F7108 +:107D8000823009F0A0C08091BF01882331F5209195 +:107D9000C101277009F497C02093E9008091EB009E +:107DA00080FF1BC0933021F48091EB00806213C0F0 +:107DB0008091EB0080618093EB0081E090E002C055 +:107DC000880F991F2A95E2F78093EA001092EA0043 +:107DD0008091EB0088608093EB001092E900809125 +:107DE000E800877F51C0882309F06DC01091BF0162 +:107DF0001F770FB7F8948091E800877F8093E800A1 +:107E00009ADD8091E80080FFFCCF8091E3008078CC +:107E1000812B8093E30080688093E300112311F4A9 +:107E200082E001C083E08EBB0FBF4DC0805882301E +:107E300008F049C08091BF019091C0016091C101DB +:107E4000AE014F5F5F4F36DDBC01009709F43BC0C8 +:107E50008091E800877F8093E80089819A8192DE93 +:107E60008091E8008B778093E8002DC0803859F529 +:107E70008091E800877F8093E8008091BB01809328 +:107E8000F1008091E8008E778093E80054DD1BC0FC +:107E90008823C9F49091BF019230A8F48091E80042 +:107EA000877F8093E8009093BB0145DD8091BB0103 +:107EB000882331F48091E30087FD02C081E001C096 +:107EC00084E08EBB50DC8091E80083FF0AC0809183 +:107ED000EB0080628093EB008091E800877F8093C5 +:107EE000E8000F900F90CF91DF911F910F910895AF +:107EF00008951F938EB3882361F01091E9001092CA +:107F0000E9008091E80083FF01C0E4DE1770109360 +:107F1000E9001F910895F999FECF92BD81BDF89AAD +:107F2000992780B50895262FF999FECF1FBA92BDE3 +:107F300081BD20BD0FB6F894FA9AF99A0FBE01964A +:067F40000895F894FFCF44 +:107F46004341544552494E41007700080000000065 +:107F56000000080112011001020000084123390047 +:107F660001000201000109023E00020100803209FF +:107F7600040000010202010005240010010424028D +:107F8600040524060001070582030800FF09040111 +:107F960000020A000000070504021000010705831D +:107FA6000210000104030904280352006F00620056 +:107FB6006F00740020004D006F0074006F007200A7 +:107FC600200042006F006100720064002000200063 +:107FD60000001803410072006400750069006E001D +:0C7FE6006F0020004C004C004300000025 +:040000030000700089 +:00000001FF diff --git a/hardware/arduino/bootloaders/caterina-Arduino_Robot/Caterina-Robot-Motor.hex b/hardware/arduino/bootloaders/caterina-Arduino_Robot/Caterina-Robot-Motor.hex new file mode 100644 index 00000000000..b5560ba4006 --- /dev/null +++ b/hardware/arduino/bootloaders/caterina-Arduino_Robot/Caterina-Robot-Motor.hex @@ -0,0 +1,258 @@ +:1070000055C000006EC000006CC000006AC00000E7 +:1070100068C0000066C0000064C0000062C00000DC +:1070200060C000005EC00000FCC400005AC0000048 +:1070300058C0000056C0000054C0000052C00000FC +:1070400050C000005DC000004CC000004AC00000FD +:1070500048C0000046C0000044C0000042C000001C +:1070600040C000003EC000003CC000003AC000002C +:1070700038C0000036C0000034C0000032C000003C +:1070800030C000002EC000002CC000002AC000004C +:1070900028C0000026C0000024C0000022C000005C +:1070A00020C000001EC000001CC0000011241FBE34 +:1070B000CFEFDAE0DEBFCDBF11E0A0E0B1E0E6E463 +:1070C000FFE702C005900D92AC3AB107D9F711E085 +:1070D000ACEAB1E001C01D92A53CB107E1F74FD386 +:1070E00030C78ECFF89410926F001092810081E02B +:1070F00085BF15BE47985D9A289A0C9400000895A4 +:107100001F920F920FB60F9211242F938F939F937C +:10711000EF93FF9310928500109284008091AC0150 +:107120009091AD01009741F001979093AD0180934C +:10713000AC01892B09F45D9A8091AE019091AF0169 +:10714000009741F001979093AF018093AE01892B96 +:1071500009F4289A8091B2019091B301019690931D +:10716000B3018093B201E0E0F0E0859194918F5FEC +:107170009F4F49F08091B0019091B1010196909399 +:10718000B1018093B001FF91EF919F918F912F9169 +:107190000F900FBE0F901F90189584E08093E90028 +:1071A0000DC08091E8008B778093E80003C08EB318 +:1071B000882351F08091E80082FFF9CF8091E800A8 +:1071C00085FFEFCF8091F1000895982F83E08093A1 +:1071D000E9008091E80085FD0DC08091E8008E7780 +:1071E0008093E80003C08EB3882369F08091E800A3 +:1071F00080FFF9CF9093F1005D9884E690E0909342 +:10720000AD018093AC0108954F925F926F927F928F +:107210008F929F92AF92BF92CF92DF92EF92FF92A6 +:107220000F931F93CF93DF9384E08093E9008091C5 +:10723000E80082FF57C2289884E690E09093AF015F +:107240008093AE01AADF182F853481F48CE49DE190 +:107250009093B1018093B00107B600FCFDCFF9997E +:10726000FECF81E180935700E89503C0843519F47F +:1072700094DF8DE00DC28C34E1F38035D1F3843797 +:1072800021F484E4A2DF80E003C2813611F489E5B1 +:10729000FFC18134B1F481DF182F7FDF90E0880FC8 +:1072A000991FAA2797FDA095BA2F312F330F20E001 +:1072B000442737FD4095542F822B932BA42BB52BBD +:1072C000B8C1803711F483E5E3C1833549F4C0E0E8 +:1072D000D1E089917ADF21E0C730D207D1F7D9C157 +:1072E000863521F481E371DF80E3D2C1833731F445 +:1072F00087E86BDF85E969DF8EE1CAC18536B9F4BD +:10730000E0E0F0E093E085E090935700E89507B661 +:1073100000FCFDCF80935700E89507B600FCFDCF39 +:10732000E058FF4FA0E7E030FA0771F7A2CF8237AD +:1073300039F4E1E0F0E089E0809357008491A8C13E +:10734000863439F4E0E0F0E089E0809357008491DE +:107350009FC18E3439F4E3E0F0E089E08093570078 +:10736000849196C1813539F4E2E0F0E089E08093C0 +:10737000570084918DC1823631F489E526DF80E0A3 +:1073800024DF80E885C1823419F0873609F0E5C032 +:107390001092B1011092B00100DF082FFEDEF82E2E +:1073A000FCDE682E8554823008F071C1902F80E099 +:1073B000CF2DD0E0C82BD92B10926F00173609F0D3 +:1073C0004BC081E180935700E895DD24CC24C39421 +:1073D0003FC0E090B501F090B6010091B701109167 +:1073E000B801B6E46B16D9F4ED2DF0E0EE29FF29D3 +:1073F000E4918E2FEADEDD2081F082E090E0A0E0D3 +:10740000B0E0E80EF91E0A1F1B1FE092B501F092D2 +:10741000B6010093B7011093B801DC2418C0D8015D +:10742000C701B695A7959795879575D5CEDE82E06D +:1074300090E0A0E0B0E0E80EF91E0A1F1B1FE092EA +:10744000B501F092B6010093B7011093B8012197EE +:10745000209709F0BECF7DC08090B5019090B60115 +:10746000A090B701B090B80196E4691609F05DC02C +:1074700083E0F40180935700E89507B600FCFDCF48 +:1074800054C0F6E46F1661F5772031F1E090B50154 +:10749000F090B6010091B7011091B8017EDED82EB0 +:1074A000CC24852D90E08C299D29F7010C01409278 +:1074B0005700E895112482E090E0A0E0B0E0E80EEB +:1074C000F91E0A1F1B1FE092B501F092B60100934E +:1074D000B7011093B80102C060DE582E742423C097 +:1074E000E090B501F090B6010091B7011091B8019C +:1074F00016950795F794E79450DE682FC70113D5CA +:107500008091B5019091B601A091B701B091B801F9 +:107510000296A11DB11D8093B5019093B601A09371 +:10752000B701B093B801219704C0552477244424AF +:107530004394209709F0A5CF96E4691641F485E0BD +:10754000F40180935700E89507B600FCFDCF8DE06D +:107550003CDE82E080936F009CC0833471F4009124 +:10756000B5011091B60119DE90E021E0F8010C019F +:1075700020935700E89511247CCE833619F5E090CE +:10758000B501F090B6010091B7011091B80105DE88 +:10759000F701E16090E021E00C0120935700E895AD +:1075A000112482E090E0A0E0B0E0E80EF91E0A1F8E +:1075B0001B1FE092B501F092B6010093B701109342 +:1075C000B80157CE8D3661F4E091B501F091B60166 +:1075D00085E080935700E89507B600FCFDCF49CEC3 +:1075E000823551F4E091B501F091B6010591149105 +:1075F000812FEBDD802F4CC0843421F5E090B50164 +:10760000F090B6010091B7011091B8011695079559 +:10761000F794E794C2DD682FC70185D48091B50146 +:107620009091B601A091B701B091B8010296A11D49 +:10763000B11D8093B5019093B601A093B701B093AB +:10764000B80117CE843609F5E090B501F090B60187 +:107650000091B7011091B801D801C701B695A7955F +:107660009795879558D4B1DD82E090E0A0E0B0E036 +:10767000E80EF91E0A1F1B1FE092B501F092B60139 +:107680000093B7011093B80104C08B3111F08FE360 +:107690009CDD83E08093E9009091E8008091E80010 +:1076A0008E778093E80095FF04C010C08EB38823C6 +:1076B000C9F08091E80080FFF9CF8091E8008E77D3 +:1076C0008093E80003C08EB3882361F08091E800C6 +:1076D00080FFF9CF84E08093E9008091E8008B7708 +:1076E0008093E800DF91CF911F910F91FF90EF9071 +:1076F000DF90CF90BF90AF909F908F907F906F90D2 +:107700005F904F9008959091BD01892F8F778132BE +:1077100049F58091BE018032A1F0813219F5913A8C +:1077200009F58091E800877F8093E8008CE091E084 +:1077300067E070E027D28091E8008B778093E800C3 +:107740000895913279F48091E800877F8093E80072 +:107750008CE091E067E070E079D28091E8008E776C +:107760008093E800089582E061EC42E0D1D083E0AC +:1077700061E842E1CDD084E060E842E1C9C01F93F6 +:10778000209100081092000844B714BE88E10FB69B +:10779000F89480936000109260000FBE80E8E0E0F3 +:1077A000F0E00FB6F89480936100E09361000FBEA3 +:1077B00031E035BF92E095BF3F9A209A559A809369 +:1077C00061001092610047985D9A289A1092890092 +:1077D0008AEF8093880090936F0083E0809381000C +:1077E000859194918F5F9F4F11F03093B401942F46 +:1077F00041FF19C0809109012817A9F08093000862 +:10780000789480911301882339F08091B20190918E +:10781000B3018F5E9240C8F310920008F89481E0A3 +:10782000809313010CC090FF04C08091B4018823A1 +:1078300051F493FF09C080910901281729F0809124 +:10784000B401882309F04EDCD4D078941092B101B1 +:107850001092B0011EEF20C0D7DC4BD38091B00155 +:107860009091B10181549F4110F0109213018091C9 +:10787000B9019091BA0101969093BA018093B90130 +:10788000292F97FF03C0512F591B252F220F28178F +:1078900010F4479801C0479A809113018823E1F6BC +:1078A0008091E00081608093E0001CDC80E090E04B +:1078B0001F910895FA01923049F0933061F09130B0 +:1078C000F9F484E191E022E130E01EC086E291E02B +:1078D0002EE330E019C0882329F484E691E024E007 +:1078E00030E012C0813029F488E691E028E230E0EF +:1078F0000BC0823029F482E991E028E130E004C035 +:1079000080E090E020E030E091838083C901089519 +:107910008093E9008091EB0081608093EB001092EE +:10792000ED006093EC004093ED008091EE00881F25 +:107930008827881F08958091BD0188238CF403C097 +:107940008EB38823B1F08091E80082FFF9CF809157 +:10795000E8008B778093E80008958EB3882349F080 +:107960008091E80080FFF9CF8091E8008E778093C6 +:10797000E8000895EF92FF920F931F9345D04CD0EB +:1079800008ED10E0F80180818F7780838081806826 +:10799000808380818F7D808319BC1EBA1092BB01C9 +:1079A00080EEE82EF12CF70180818B7F8083F80137 +:1079B00080818160808380E060E042E0A9DFE1EEC9 +:1079C000F0E080818E7F8083E2EEF0E08081816054 +:1079D0008083808188608083F70180818E7F8083AF +:1079E000F8018081806180831F910F91FF90EF905B +:1079F0000895E7EDF0E08081816080838AE482BFB2 +:107A000081E08093BC01B6CFE8EDF0E080818E7F0D +:107A100080831092E20008951092DA001092E10043 +:107A200008951F920F920FB60F9211242F933F9338 +:107A30004F935F936F937F938F939F93AF93BF9376 +:107A4000EF93FF938091DA0080FF1BC08091D800F4 +:107A500080FF17C08091DA008E7F8093DA008091DA +:107A6000D90080FF0BC080E189BD82E189BD09B4E6 +:107A700000FEFDCF81E08EBB3BD203C019BC1EBA15 +:107A800037D28091E10080FF17C08091E20080FF33 +:107A900013C08091E2008E7F8093E2008091E2002B +:107AA00080618093E2008091D80080628093D8004A +:107AB00019BC85E08EBB1CD28091E10084FF2CC0F4 +:107AC0008091E20084FF28C080E189BD82E189BD08 +:107AD00009B400FEFDCF8091D8008F7D8093D8003F +:107AE0008091E1008F7E8093E1008091E2008F7EA3 +:107AF0008093E2008091E20081608093E2008091B7 +:107B0000BB01882331F48091E30087FD02C081E04E +:107B100001C084E08EBBECD18091E10083FF21C0E5 +:107B20008091E20083FF1DC08091E100877F8093F8 +:107B3000E10082E08EBB1092BB018091E1008E7F5C +:107B40008093E1008091E2008E7F8093E20080913B +:107B5000E20080618093E20080E060E042E0D8DEF5 +:107B6000C7D1FF91EF91BF91AF919F918F917F917D +:107B70006F915F914F913F912F910F900FBE0F909A +:107B80001F9018959C014091C3015091C401461764 +:107B9000570718F4F90190E044C06115710511F020 +:107BA000AB01F8CF8091E8008E778093E80040E049 +:107BB00050E0F0CF8EB3882309F444C0853009F437 +:107BC00043C08091E80083FF02C081E00895809166 +:107BD000E80082FD31C08091E80080FF22C08091E2 +:107BE000F3009091F200782F60E0292F30E0262BEF +:107BF000372B07C081918093F100415050402F5F97 +:107C00003F4F4115510519F02830310598F390E0A8 +:107C10002830310509F491E08091E8008E77809357 +:107C2000E8004115510531F6992321F605C08EB3C0 +:107C3000882341F0853041F08091E80082FFF7CF42 +:107C400080E0089582E0089583E008959C01611525 +:107C5000710529F48091E8008B778093E800F901A1 +:107C600026C08EB3882391F1853091F18091E80090 +:107C700083FF02C081E008958091E80082FFF1CF88 +:107C800006C08091F10081936150704059F02091BD +:107C9000F3008091F200322F20E090E0822B932BB2 +:107CA000892B79F78091E8008B778093E800611544 +:107CB0007105B9F605C08EB3882341F0853041F0D7 +:107CC0008091E80080FFF7CF80E0089582E008957A +:107CD00083E008950F931F93DF93CF9300D0CDB728 +:107CE000DEB7EDEBF1E08091F100819381E0E53CBE +:107CF000F807C9F708DD8091E80083FFE4C08091B0 +:107D0000BD019091BE01953009F46DC0963040F4EC +:107D1000913081F1913070F0933009F0D4C02AC0D5 +:107D2000983009F4A3C0993009F4B2C0963009F034 +:107D3000CAC07CC0803809F4C6C0823809F0C3C00C +:107D40008091C10187708093E9008091EB001092CF +:107D5000E9002091E800277F2093E80090E025E0EB +:107D6000969587952A95E1F781708093F10010929E +:107D7000F10087C0882319F0823009F0A4C08F7108 +:107D8000823009F0A0C08091BF01882331F5209195 +:107D9000C101277009F497C02093E9008091EB009E +:107DA00080FF1BC0933021F48091EB00806213C0F0 +:107DB0008091EB0080618093EB0081E090E002C055 +:107DC000880F991F2A95E2F78093EA001092EA0043 +:107DD0008091EB0088608093EB001092E900809125 +:107DE000E800877F51C0882309F06DC01091BF0162 +:107DF0001F770FB7F8948091E800877F8093E800A1 +:107E00009ADD8091E80080FFFCCF8091E3008078CC +:107E1000812B8093E30080688093E300112311F4A9 +:107E200082E001C083E08EBB0FBF4DC0805882301E +:107E300008F049C08091BF019091C0016091C101DB +:107E4000AE014F5F5F4F36DDBC01009709F43BC0C8 +:107E50008091E800877F8093E80089819A8192DE93 +:107E60008091E8008B778093E8002DC0803859F529 +:107E70008091E800877F8093E8008091BB01809328 +:107E8000F1008091E8008E778093E80054DD1BC0FC +:107E90008823C9F49091BF019230A8F48091E80042 +:107EA000877F8093E8009093BB0145DD8091BB0103 +:107EB000882331F48091E30087FD02C081E001C096 +:107EC00084E08EBB50DC8091E80083FF0AC0809183 +:107ED000EB0080628093EB008091E800877F8093C5 +:107EE000E8000F900F90CF91DF911F910F910895AF +:107EF00008951F938EB3882361F01091E9001092CA +:107F0000E9008091E80083FF01C0E4DE1770109360 +:107F1000E9001F910895F999FECF92BD81BDF89AAD +:107F2000992780B50895262FF999FECF1FBA92BDE3 +:107F300081BD20BD0FB6F894FA9AF99A0FBE01964A +:067F40000895F894FFCF44 +:107F46004341544552494E41007700080000000065 +:107F56000000080112011001020000084123380048 +:107F660001000201000109023E00020100803209FF +:107F7600040000010202010005240010010424028D +:107F8600040524060001070582030800FF09040111 +:107F960000020A000000070504021000010705831D +:107FA6000210000104030904280352006F00620056 +:107FB6006F007400200043006F006E0074007200B2 +:107FC6006F006C00200042006F00610072006400C8 +:107FD60000001803410072006400750069006E001D +:0C7FE6006F0020004C004C004300000025 +:040000030000700089 +:00000001FF diff --git a/hardware/arduino/bootloaders/caterina-Arduino_Robot/Caterina-Robot.txt b/hardware/arduino/bootloaders/caterina-Arduino_Robot/Caterina-Robot.txt new file mode 100644 index 00000000000..5beb659a081 --- /dev/null +++ b/hardware/arduino/bootloaders/caterina-Arduino_Robot/Caterina-Robot.txt @@ -0,0 +1,11 @@ +Builds against LUFA version 111009 +make version 3.81 +avrdude version 5.11 + +All AVR tools except avrdude were installed by CrossPack 20100115: +avr-gcc version 4.3.3 (GCC) +Thread model: single +Configured with: ../configure —prefix=/usr/local/CrossPack-AVR-20100115 —disable-dependency-tracking —disable-nls —disable-werror —target=avr —enable-languages=c,c++ —disable-nls —disable-libssp —with-dwarf2 +avr-libc version 1.6.7 +binutils version 2.19 + diff --git a/hardware/arduino/bootloaders/caterina-Arduino_Robot/Caterina.c b/hardware/arduino/bootloaders/caterina-Arduino_Robot/Caterina.c new file mode 100644 index 00000000000..c462420ff55 --- /dev/null +++ b/hardware/arduino/bootloaders/caterina-Arduino_Robot/Caterina.c @@ -0,0 +1,780 @@ +/* + LUFA Library + Copyright (C) Dean Camera, 2011. + + dean [at] fourwalledcubicle [dot] com + www.lufa-lib.org +*/ + +/* + Copyright 2011 Dean Camera (dean [at] fourwalledcubicle [dot] com) + + Permission to use, copy, modify, distribute, and sell this + software and its documentation for any purpose is hereby granted + without fee, provided that the above copyright notice appear in + all copies and that both that the copyright notice and this + permission notice and warranty disclaimer appear in supporting + documentation, and that the name of the author not be used in + advertising or publicity pertaining to distribution of the + software without specific, written prior permission. + + The author disclaim all warranties with regard to this + software, including all implied warranties of merchantability + and fitness. In no event shall the author be liable for any + special, indirect or consequential damages or any damages + whatsoever resulting from loss of use, data or profits, whether + in an action of contract, negligence or other tortious action, + arising out of or in connection with the use or performance of + this software. +*/ + +/** \file + * + * Main source file for the CDC class bootloader. This file contains the complete bootloader logic. + */ + +#define INCLUDE_FROM_CATERINA_C +#include "Caterina.h" + +/** Contains the current baud rate and other settings of the first virtual serial port. This must be retained as some + * operating systems will not open the port unless the settings can be set successfully. + */ +static CDC_LineEncoding_t LineEncoding = { .BaudRateBPS = 0, + .CharFormat = CDC_LINEENCODING_OneStopBit, + .ParityType = CDC_PARITY_None, + .DataBits = 8 }; + +/** Current address counter. This stores the current address of the FLASH or EEPROM as set by the host, + * and is used when reading or writing to the AVRs memory (either FLASH or EEPROM depending on the issued + * command.) + */ +static uint32_t CurrAddress; + +/** Flag to indicate if the bootloader should be running, or should exit and allow the application code to run + * via a watchdog reset. When cleared the bootloader will exit, starting the watchdog and entering an infinite + * loop until the AVR restarts and the application runs. + */ +static bool RunBootloader = true; + +/* Pulse generation counters to keep track of the time remaining for each pulse type */ +#define TX_RX_LED_PULSE_PERIOD 100 +uint16_t TxLEDPulse = 0; // time remaining for Tx LED pulse +uint16_t RxLEDPulse = 0; // time remaining for Rx LED pulse + +/* Bootloader timeout timer */ +// MAH 8/15/12- change so timeouts work properly when the chip is running at 8MHz instead of 16. +#define TIMEOUT_PERIOD 8000 +#define EXT_RESET_TIMEOUT_PERIOD 750 + + +/********************************************************************************************************* +LilyPadUSB bootloader code +The LilyPadUSB bootloader has been changed to remove the 8-second delay after external reset which is in +the Leonardo. To enter the bootloader, the user should execute TWO external resets within 750 ms; that is, +press the reset button twice, quickly.\ + +Some other changes were made to allow this code to compile tightly enough to fit in the alloted 4k of +bootloader space. +*/ +// MAH 8/15/12- added this flag to replace the bulky program memory reads to check for the presence of a sketch +// at the top of the memory space. +static bool sketchPresent = false; + +// MAH 8/15/12- make this volatile, since we modify it in one place and read it in another, we want to make +// sure we're always working on the copy in memory and not an erroneous value stored in a cache somewhere. +// This variable stores the length of time we've been in the bootloader when waiting for the 8 second delay. +volatile uint16_t Timeout = 0; +// MAH 8/15/12- added this for delay during startup. Did not use existing Timeout value b/c it only increments +// when there's a sketch at the top of the memory. +volatile uint16_t resetTimeout = 0; + +// MAH 8/15/12- let's make this an 8-bit value instead of 16- that saves on memory because 16-bit addition and +// comparison compiles to bulkier code. Note that this does *not* require a change to the Arduino core- we're +// just sort of ignoring the extra byte that the Arduino core puts at the next location. +uint8_t bootKey = 0x77; +volatile uint8_t *const bootKeyPtr = (volatile uint8_t *)0x0800; + +// StartSketch() is called to clean up our mess before passing execution to the sketch. +void StartSketch(void) +{ + cli(); + + /* Undo TIMER1 setup and clear the count before running the sketch */ + TIMSK1 = 0; + TCCR1B = 0; + + /* Relocate the interrupt vector table to the application section */ + MCUCR = (1 << IVCE); + MCUCR = 0; + + L_LED_OFF(); + TX_LED_OFF(); + RX_LED_OFF(); + + /* jump to beginning of application space */ + __asm__ volatile("jmp 0x0000"); + +} + +uint16_t LLEDPulse; + +/** Main program entry point. This routine configures the hardware required by the bootloader, then continuously + * runs the bootloader processing routine until it times out or is instructed to exit. + */ +int main(void) +{ + /* Save the value of the boot key memory before it is overwritten */ + uint8_t bootKeyPtrVal = *bootKeyPtr; + *bootKeyPtr = 0; + + /* Check the reason for the reset so we can act accordingly */ + uint8_t mcusr_state = MCUSR; // store the initial state of the Status register + MCUSR = 0; // clear all reset flags + + /* Watchdog may be configured with a 15 ms period so must disable it before going any further */ + // MAH 8/15/12- I removed this because wdt_disable() is the first thing SetupHardware() does- why + // do it twice right in a row? + //wdt_disable(); + + /* Setup hardware required for the bootloader */ + // MAH 8/15/12- Moved this up to before the bootloader go/no-go decision tree so I could use the + // timer in that decision tree. Removed the USBInit() call from it; if I'm not going to stay in + // the bootloader, there's no point spending the time initializing the USB. + // SetupHardware(); + wdt_disable(); + + // Disable clock division + clock_prescale_set(clock_div_1); + + // Relocate the interrupt vector table to the bootloader section + MCUCR = (1 << IVCE); + MCUCR = (1 << IVSEL); + + LED_SETUP(); + CPU_PRESCALE(0); + L_LED_OFF(); + TX_LED_OFF(); + RX_LED_OFF(); + + // Initialize TIMER1 to handle bootloader timeout and LED tasks. + // With 16 MHz clock and 1/64 prescaler, timer 1 is clocked at 250 kHz + // Our chosen compare match generates an interrupt every 1 ms. + // This interrupt is disabled selectively when doing memory reading, erasing, + // or writing since SPM has tight timing requirements. + + OCR1AH = 0; + OCR1AL = 250; + TIMSK1 = (1 << OCIE1A); // enable timer 1 output compare A match interrupt + TCCR1B = ((1 << CS11) | (1 << CS10)); // 1/64 prescaler on timer 1 input + + + // MAH 8/15/12- this replaces bulky pgm_read_word(0) calls later on, to save memory. + if (pgm_read_word(0) != 0xFFFF) sketchPresent = true; + +// MAH 26 Oct 2012- The "bootload or not?" section has been modified since the code released +// with Arduino 1.0.1. The simplest modification is the replacement of equivalence checks on +// the reset bits with masked checks, so if more than one reset occurs before the register is +// checked, the check doesn't fail and fall through to the bootloader unnecessarily. + +// The second, more in depth modification addresses behavior after an external reset (i.e., +// user pushes the reset button). The Leonardo treats all external resets as requests to +// re-enter the bootloader and wait for code to be loaded. It remains in bootloader mode for +// 8 seconds before continuing on to the sketch (if one is present). By defining RESET_DELAY +// equal to 1, this behavior will persist. + +// However, if RESET_DELAY is defined to 0, the reset timeout before loading the sketch drops +// to 750ms. If, during that 750ms, another external reset occurs, THEN an 8-second delay +// in the bootloader will occur. + + // This is the "no-8-second-delay" code. If this is the first time through the loop, we + // don't expect to see the bootKey in memory. + if ( (mcusr_state & (1< EXT_RESET_TIMEOUT_PERIOD) // resetTimeout is getting incremeted + RunBootloader = false; // in the timer1 ISR. + } + // If we make it past that while loop, it's sketch loading time! + *bootKeyPtr = 0; // clear out the bootKey; from now on, we want to treat a reset like + // a normal reset. + cli(); // Disable interrupts, in case no sketch is present. + RunBootloader = true; // We want to hang out in the bootloader if no sketch is present. + if (sketchPresent) StartSketch(); // If a sketch is present, go! Otherwise, wait around + // in the bootloader until one is uploaded. + } + // On a power-on reset, we ALWAYS want to go to the sketch. If there is one. + // This is a place where the old code had an equivalence and now there is a mask. + else if ( (mcusr_state & (1< TIMEOUT_PERIOD) + RunBootloader = false; + + // MAH 8/15/12- This used to be a function call- inlining it saves a few bytes. + LLEDPulse++; + uint8_t p = LLEDPulse >> 8; + if (p > 127) + p = 254-p; + p += p; + if (((uint8_t)LLEDPulse) > p) + L_LED_OFF(); + else + L_LED_ON(); + } + + /* Disconnect from the host - USB interface will be reset later along with the AVR */ + USB_Detach(); + + /* Jump to beginning of application space to run the sketch - do not reset */ + StartSketch(); +} + +// Timer1 is set up to provide periodic interrupts. This is used to flicker the LEDs during +// programming as well as to generate the clock counts which determine how long the board should +// remain in bootloading mode. + +ISR(TIMER1_COMPA_vect, ISR_BLOCK) +{ + /* Reset counter */ + TCNT1H = 0; + TCNT1L = 0; + + /* Check whether the TX or RX LED one-shot period has elapsed. if so, turn off the LED */ + if (TxLEDPulse && !(--TxLEDPulse)) + TX_LED_OFF(); + if (RxLEDPulse && !(--RxLEDPulse)) + RX_LED_OFF(); + resetTimeout++; // Needed for the "short reset delay" mode- governs the time the board waits + // for a second reset before loading the sketch. + if (pgm_read_word(0) != 0xFFFF) + Timeout++; +} + +// MAH 29 Oct 2012 Nothing below this point has to change for the LilyPadUSB support + +/** Event handler for the USB_ConfigurationChanged event. This configures the device's endpoints ready + * to relay data to and from the attached USB host. + */ +void EVENT_USB_Device_ConfigurationChanged(void) +{ + /* Setup CDC Notification, Rx and Tx Endpoints */ + Endpoint_ConfigureEndpoint(CDC_NOTIFICATION_EPNUM, EP_TYPE_INTERRUPT, + ENDPOINT_DIR_IN, CDC_NOTIFICATION_EPSIZE, + ENDPOINT_BANK_SINGLE); + + Endpoint_ConfigureEndpoint(CDC_TX_EPNUM, EP_TYPE_BULK, + ENDPOINT_DIR_IN, CDC_TXRX_EPSIZE, + ENDPOINT_BANK_SINGLE); + + Endpoint_ConfigureEndpoint(CDC_RX_EPNUM, EP_TYPE_BULK, + ENDPOINT_DIR_OUT, CDC_TXRX_EPSIZE, + ENDPOINT_BANK_SINGLE); +} + +/** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to + * the device from the USB host before passing along unhandled control requests to the library for processing + * internally. + */ +void EVENT_USB_Device_ControlRequest(void) +{ + /* Ignore any requests that aren't directed to the CDC interface */ + if ((USB_ControlRequest.bmRequestType & (CONTROL_REQTYPE_TYPE | CONTROL_REQTYPE_RECIPIENT)) != + (REQTYPE_CLASS | REQREC_INTERFACE)) + { + return; + } + + /* Process CDC specific control requests */ + switch (USB_ControlRequest.bRequest) + { + case CDC_REQ_GetLineEncoding: + if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE)) + { + Endpoint_ClearSETUP(); + + /* Write the line coding data to the control endpoint */ + Endpoint_Write_Control_Stream_LE(&LineEncoding, sizeof(CDC_LineEncoding_t)); + Endpoint_ClearOUT(); + } + + break; + case CDC_REQ_SetLineEncoding: + if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE)) + { + Endpoint_ClearSETUP(); + + /* Read the line coding data in from the host into the global struct */ + Endpoint_Read_Control_Stream_LE(&LineEncoding, sizeof(CDC_LineEncoding_t)); + Endpoint_ClearIN(); + } + + break; + } +} + +#if !defined(NO_BLOCK_SUPPORT) +/** Reads or writes a block of EEPROM or FLASH memory to or from the appropriate CDC data endpoint, depending + * on the AVR910 protocol command issued. + * + * \param[in] Command Single character AVR910 protocol command indicating what memory operation to perform + */ +static void ReadWriteMemoryBlock(const uint8_t Command) +{ + uint16_t BlockSize; + char MemoryType; + + bool HighByte = false; + uint8_t LowByte = 0; + + BlockSize = (FetchNextCommandByte() << 8); + BlockSize |= FetchNextCommandByte(); + + MemoryType = FetchNextCommandByte(); + + if ((MemoryType != 'E') && (MemoryType != 'F')) + { + /* Send error byte back to the host */ + WriteNextResponseByte('?'); + + return; + } + + /* Disable timer 1 interrupt - can't afford to process nonessential interrupts + * while doing SPM tasks */ + TIMSK1 = 0; + + /* Check if command is to read memory */ + if (Command == 'g') + { + /* Re-enable RWW section */ + boot_rww_enable(); + + while (BlockSize--) + { + if (MemoryType == 'F') + { + /* Read the next FLASH byte from the current FLASH page */ + #if (FLASHEND > 0xFFFF) + WriteNextResponseByte(pgm_read_byte_far(CurrAddress | HighByte)); + #else + WriteNextResponseByte(pgm_read_byte(CurrAddress | HighByte)); + #endif + + /* If both bytes in current word have been read, increment the address counter */ + if (HighByte) + CurrAddress += 2; + + HighByte = !HighByte; + } + else + { + /* Read the next EEPROM byte into the endpoint */ + WriteNextResponseByte(eeprom_read_byte((uint8_t*)(intptr_t)(CurrAddress >> 1))); + + /* Increment the address counter after use */ + CurrAddress += 2; + } + } + } + else + { + uint32_t PageStartAddress = CurrAddress; + + if (MemoryType == 'F') + { + boot_page_erase(PageStartAddress); + boot_spm_busy_wait(); + } + + while (BlockSize--) + { + if (MemoryType == 'F') + { + /* If both bytes in current word have been written, increment the address counter */ + if (HighByte) + { + /* Write the next FLASH word to the current FLASH page */ + boot_page_fill(CurrAddress, ((FetchNextCommandByte() << 8) | LowByte)); + + /* Increment the address counter after use */ + CurrAddress += 2; + } + else + { + LowByte = FetchNextCommandByte(); + } + + HighByte = !HighByte; + } + else + { + /* Write the next EEPROM byte from the endpoint */ + eeprom_write_byte((uint8_t*)((intptr_t)(CurrAddress >> 1)), FetchNextCommandByte()); + + /* Increment the address counter after use */ + CurrAddress += 2; + } + } + + /* If in FLASH programming mode, commit the page after writing */ + if (MemoryType == 'F') + { + /* Commit the flash page to memory */ + boot_page_write(PageStartAddress); + + /* Wait until write operation has completed */ + boot_spm_busy_wait(); + } + + /* Send response byte back to the host */ + WriteNextResponseByte('\r'); + } + + /* Re-enable timer 1 interrupt disabled earlier in this routine */ + TIMSK1 = (1 << OCIE1A); +} +#endif + +/** Retrieves the next byte from the host in the CDC data OUT endpoint, and clears the endpoint bank if needed + * to allow reception of the next data packet from the host. + * + * \return Next received byte from the host in the CDC data OUT endpoint + */ +static uint8_t FetchNextCommandByte(void) +{ + /* Select the OUT endpoint so that the next data byte can be read */ + Endpoint_SelectEndpoint(CDC_RX_EPNUM); + + /* If OUT endpoint empty, clear it and wait for the next packet from the host */ + while (!(Endpoint_IsReadWriteAllowed())) + { + Endpoint_ClearOUT(); + + while (!(Endpoint_IsOUTReceived())) + { + if (USB_DeviceState == DEVICE_STATE_Unattached) + return 0; + } + } + + /* Fetch the next byte from the OUT endpoint */ + return Endpoint_Read_8(); +} + +/** Writes the next response byte to the CDC data IN endpoint, and sends the endpoint back if needed to free up the + * bank when full ready for the next byte in the packet to the host. + * + * \param[in] Response Next response byte to send to the host + */ +static void WriteNextResponseByte(const uint8_t Response) +{ + /* Select the IN endpoint so that the next data byte can be written */ + Endpoint_SelectEndpoint(CDC_TX_EPNUM); + + /* If IN endpoint full, clear it and wait until ready for the next packet to the host */ + if (!(Endpoint_IsReadWriteAllowed())) + { + Endpoint_ClearIN(); + + while (!(Endpoint_IsINReady())) + { + if (USB_DeviceState == DEVICE_STATE_Unattached) + return; + } + } + + /* Write the next byte to the IN endpoint */ + Endpoint_Write_8(Response); + + TX_LED_ON(); + TxLEDPulse = TX_RX_LED_PULSE_PERIOD; +} + +#define STK_OK 0x10 +#define STK_INSYNC 0x14 // ' ' +#define CRC_EOP 0x20 // 'SPACE' +#define STK_GET_SYNC 0x30 // '0' + +#define STK_GET_PARAMETER 0x41 // 'A' +#define STK_SET_DEVICE 0x42 // 'B' +#define STK_SET_DEVICE_EXT 0x45 // 'E' +#define STK_LOAD_ADDRESS 0x55 // 'U' +#define STK_UNIVERSAL 0x56 // 'V' +#define STK_PROG_PAGE 0x64 // 'd' +#define STK_READ_PAGE 0x74 // 't' +#define STK_READ_SIGN 0x75 // 'u' + +/** Task to read in AVR910 commands from the CDC data OUT endpoint, process them, perform the required actions + * and send the appropriate response back to the host. + */ +void CDC_Task(void) +{ + /* Select the OUT endpoint */ + Endpoint_SelectEndpoint(CDC_RX_EPNUM); + + /* Check if endpoint has a command in it sent from the host */ + if (!(Endpoint_IsOUTReceived())) + return; + + RX_LED_ON(); + RxLEDPulse = TX_RX_LED_PULSE_PERIOD; + + /* Read in the bootloader command (first byte sent from host) */ + uint8_t Command = FetchNextCommandByte(); + + if (Command == 'E') + { + /* We nearly run out the bootloader timeout clock, + * leaving just a few hundred milliseconds so the + * bootloder has time to respond and service any + * subsequent requests */ + Timeout = TIMEOUT_PERIOD - 500; + + /* Re-enable RWW section - must be done here in case + * user has disabled verification on upload. */ + boot_rww_enable_safe(); + + // Send confirmation byte back to the host + WriteNextResponseByte('\r'); + } + else if (Command == 'T') + { + FetchNextCommandByte(); + + // Send confirmation byte back to the host + WriteNextResponseByte('\r'); + } + else if ((Command == 'L') || (Command == 'P')) + { + // Send confirmation byte back to the host + WriteNextResponseByte('\r'); + } + else if (Command == 't') + { + // Return ATMEGA128 part code - this is only to allow AVRProg to use the bootloader + WriteNextResponseByte(0x44); + WriteNextResponseByte(0x00); + } + else if (Command == 'a') + { + // Indicate auto-address increment is supported + WriteNextResponseByte('Y'); + } + else if (Command == 'A') + { + // Set the current address to that given by the host + CurrAddress = (FetchNextCommandByte() << 9); + CurrAddress |= (FetchNextCommandByte() << 1); + + // Send confirmation byte back to the host + WriteNextResponseByte('\r'); + } + else if (Command == 'p') + { + // Indicate serial programmer back to the host + WriteNextResponseByte('S'); + } + else if (Command == 'S') + { + // Write the 7-byte software identifier to the endpoint + for (uint8_t CurrByte = 0; CurrByte < 7; CurrByte++) + WriteNextResponseByte(SOFTWARE_IDENTIFIER[CurrByte]); + } + else if (Command == 'V') + { + WriteNextResponseByte('0' + BOOTLOADER_VERSION_MAJOR); + WriteNextResponseByte('0' + BOOTLOADER_VERSION_MINOR); + } + else if (Command == 's') + { + WriteNextResponseByte(AVR_SIGNATURE_3); + WriteNextResponseByte(AVR_SIGNATURE_2); + WriteNextResponseByte(AVR_SIGNATURE_1); + } + else if (Command == 'e') + { + // Clear the application section of flash + for (uint32_t CurrFlashAddress = 0; CurrFlashAddress < BOOT_START_ADDR; CurrFlashAddress += SPM_PAGESIZE) + { + boot_page_erase(CurrFlashAddress); + boot_spm_busy_wait(); + boot_page_write(CurrFlashAddress); + boot_spm_busy_wait(); + } + + // Send confirmation byte back to the host + WriteNextResponseByte('\r'); + } + #if !defined(NO_LOCK_BYTE_WRITE_SUPPORT) + else if (Command == 'l') + { + // Set the lock bits to those given by the host + boot_lock_bits_set(FetchNextCommandByte()); + + // Send confirmation byte back to the host + WriteNextResponseByte('\r'); + } + #endif + else if (Command == 'r') + { + WriteNextResponseByte(boot_lock_fuse_bits_get(GET_LOCK_BITS)); + } + else if (Command == 'F') + { + WriteNextResponseByte(boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS)); + } + else if (Command == 'N') + { + WriteNextResponseByte(boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS)); + } + else if (Command == 'Q') + { + WriteNextResponseByte(boot_lock_fuse_bits_get(GET_EXTENDED_FUSE_BITS)); + } + #if !defined(NO_BLOCK_SUPPORT) + else if (Command == 'b') + { + WriteNextResponseByte('Y'); + + // Send block size to the host + WriteNextResponseByte(SPM_PAGESIZE >> 8); + WriteNextResponseByte(SPM_PAGESIZE & 0xFF); + } + else if ((Command == 'B') || (Command == 'g')) + { + // Keep resetting the timeout counter if we're receiving self-programming instructions + Timeout = 0; + // Delegate the block write/read to a separate function for clarity + ReadWriteMemoryBlock(Command); + } + #endif + #if !defined(NO_FLASH_BYTE_SUPPORT) + else if (Command == 'C') + { + // Write the high byte to the current flash page + boot_page_fill(CurrAddress, FetchNextCommandByte()); + + // Send confirmation byte back to the host + WriteNextResponseByte('\r'); + } + else if (Command == 'c') + { + // Write the low byte to the current flash page + boot_page_fill(CurrAddress | 0x01, FetchNextCommandByte()); + + // Increment the address + CurrAddress += 2; + + // Send confirmation byte back to the host + WriteNextResponseByte('\r'); + } + else if (Command == 'm') + { + // Commit the flash page to memory + boot_page_write(CurrAddress); + + // Wait until write operation has completed + boot_spm_busy_wait(); + + // Send confirmation byte back to the host + WriteNextResponseByte('\r'); + } + else if (Command == 'R') + { + #if (FLASHEND > 0xFFFF) + uint16_t ProgramWord = pgm_read_word_far(CurrAddress); + #else + uint16_t ProgramWord = pgm_read_word(CurrAddress); + #endif + + WriteNextResponseByte(ProgramWord >> 8); + WriteNextResponseByte(ProgramWord & 0xFF); + } + #endif + #if !defined(NO_EEPROM_BYTE_SUPPORT) + else if (Command == 'D') + { + // Read the byte from the endpoint and write it to the EEPROM + eeprom_write_byte((uint8_t*)((intptr_t)(CurrAddress >> 1)), FetchNextCommandByte()); + + // Increment the address after use + CurrAddress += 2; + + // Send confirmation byte back to the host + WriteNextResponseByte('\r'); + } + else if (Command == 'd') + { + // Read the EEPROM byte and write it to the endpoint + WriteNextResponseByte(eeprom_read_byte((uint8_t*)((intptr_t)(CurrAddress >> 1)))); + + // Increment the address after use + CurrAddress += 2; + } + #endif + else if (Command != 27) + { + // Unknown (non-sync) command, return fail code + WriteNextResponseByte('?'); + } + + + /* Select the IN endpoint */ + Endpoint_SelectEndpoint(CDC_TX_EPNUM); + + /* Remember if the endpoint is completely full before clearing it */ + bool IsEndpointFull = !(Endpoint_IsReadWriteAllowed()); + + /* Send the endpoint data to the host */ + Endpoint_ClearIN(); + + /* If a full endpoint's worth of data was sent, we need to send an empty packet afterwards to signal end of transfer */ + if (IsEndpointFull) + { + while (!(Endpoint_IsINReady())) + { + if (USB_DeviceState == DEVICE_STATE_Unattached) + return; + } + + Endpoint_ClearIN(); + } + + /* Wait until the data has been sent to the host */ + while (!(Endpoint_IsINReady())) + { + if (USB_DeviceState == DEVICE_STATE_Unattached) + return; + } + + /* Select the OUT endpoint */ + Endpoint_SelectEndpoint(CDC_RX_EPNUM); + + /* Acknowledge the command from the host */ + Endpoint_ClearOUT(); +} + diff --git a/hardware/arduino/bootloaders/caterina-Arduino_Robot/Caterina.h b/hardware/arduino/bootloaders/caterina-Arduino_Robot/Caterina.h new file mode 100644 index 00000000000..5ce80fab609 --- /dev/null +++ b/hardware/arduino/bootloaders/caterina-Arduino_Robot/Caterina.h @@ -0,0 +1,106 @@ +/* + LUFA Library + Copyright (C) Dean Camera, 2011. + + dean [at] fourwalledcubicle [dot] com + www.lufa-lib.org +*/ + +/* + Copyright 2011 Dean Camera (dean [at] fourwalledcubicle [dot] com) + + Permission to use, copy, modify, distribute, and sell this + software and its documentation for any purpose is hereby granted + without fee, provided that the above copyright notice appear in + all copies and that both that the copyright notice and this + permission notice and warranty disclaimer appear in supporting + documentation, and that the name of the author not be used in + advertising or publicity pertaining to distribution of the + software without specific, written prior permission. + + The author disclaim all warranties with regard to this + software, including all implied warranties of merchantability + and fitness. In no event shall the author be liable for any + special, indirect or consequential damages or any damages + whatsoever resulting from loss of use, data or profits, whether + in an action of contract, negligence or other tortious action, + arising out of or in connection with the use or performance of + this software. +*/ + +/** \file + * + * Header file for BootloaderCDC.c. + */ + +#ifndef _CDC_H_ +#define _CDC_H_ + + /* Includes: */ + #include + #include + #include + #include + #include + #include + #include + + #include "Descriptors.h" + + #include + /* Macros: */ + /** Version major of the CDC bootloader. */ + #define BOOTLOADER_VERSION_MAJOR 0x01 + + /** Version minor of the CDC bootloader. */ + #define BOOTLOADER_VERSION_MINOR 0x00 + + /** Hardware version major of the CDC bootloader. */ + #define BOOTLOADER_HWVERSION_MAJOR 0x01 + + /** Hardware version minor of the CDC bootloader. */ + #define BOOTLOADER_HWVERSION_MINOR 0x00 + + /** Eight character bootloader firmware identifier reported to the host when requested */ + #define SOFTWARE_IDENTIFIER "CATERINA" + + #define CPU_PRESCALE(n) (CLKPR = 0x80, CLKPR = (n)) + #define LED_SETUP() DDRC |= (1<<7); DDRB |= (1<<0); DDRD |= (1<<5); + #define L_LED_OFF() PORTC &= ~(1<<7) + #define L_LED_ON() PORTC |= (1<<7) + #define L_LED_TOGGLE() PORTC ^= (1<<7) + #if DEVICE_PID == 0x0037 // polarity of the RX and TX LEDs is reversed on the Micro + #define TX_LED_OFF() PORTD &= ~(1<<5) + #define TX_LED_ON() PORTD |= (1<<5) + #define RX_LED_OFF() PORTB &= ~(1<<0) + #define RX_LED_ON() PORTB |= (1<<0) + #else + #define TX_LED_OFF() PORTD |= (1<<5) + #define TX_LED_ON() PORTD &= ~(1<<5) + #define RX_LED_OFF() PORTB |= (1<<0) + #define RX_LED_ON() PORTB &= ~(1<<0) + #endif + + /* Type Defines: */ + /** Type define for a non-returning pointer to the start of the loaded application in flash memory. */ + typedef void (*AppPtr_t)(void) ATTR_NO_RETURN; + + /* Function Prototypes: */ + void StartSketch(void); + void LEDPulse(void); + + void CDC_Task(void); + void SetupHardware(void); + + void EVENT_USB_Device_ConfigurationChanged(void); + + #if defined(INCLUDE_FROM_CATERINA_C) || defined(__DOXYGEN__) + #if !defined(NO_BLOCK_SUPPORT) + static void ReadWriteMemoryBlock(const uint8_t Command); + #endif + static uint8_t FetchNextCommandByte(void); + static void WriteNextResponseByte(const uint8_t Response); + #endif + +#endif + diff --git a/hardware/arduino/bootloaders/caterina-Arduino_Robot/Descriptors.c b/hardware/arduino/bootloaders/caterina-Arduino_Robot/Descriptors.c new file mode 100644 index 00000000000..57f39d98af4 --- /dev/null +++ b/hardware/arduino/bootloaders/caterina-Arduino_Robot/Descriptors.c @@ -0,0 +1,270 @@ +/* + LUFA Library + Copyright (C) Dean Camera, 2011. + + dean [at] fourwalledcubicle [dot] com + www.lufa-lib.org +*/ + +/* + Copyright 2011 Dean Camera (dean [at] fourwalledcubicle [dot] com) + + Permission to use, copy, modify, distribute, and sell this + software and its documentation for any purpose is hereby granted + without fee, provided that the above copyright notice appear in + all copies and that both that the copyright notice and this + permission notice and warranty disclaimer appear in supporting + documentation, and that the name of the author not be used in + advertising or publicity pertaining to distribution of the + software without specific, written prior permission. + + The author disclaim all warranties with regard to this + software, including all implied warranties of merchantability + and fitness. In no event shall the author be liable for any + special, indirect or consequential damages or any damages + whatsoever resulting from loss of use, data or profits, whether + in an action of contract, negligence or other tortious action, + arising out of or in connection with the use or performance of + this software. +*/ + +/** \file + * + * USB Device Descriptors, for library use when in USB device mode. Descriptors are special + * computer-readable structures which the host requests upon device enumeration, to determine + * the device's capabilities and functions. + */ + +#include "Descriptors.h" + +/** Device descriptor structure. This descriptor, located in SRAM memory, describes the overall + * device characteristics, including the supported USB version, control endpoint size and the + * number of device configurations. The descriptor is read out by the USB host when the enumeration + * process begins. + */ +const USB_Descriptor_Device_t DeviceDescriptor = +{ + .Header = {.Size = sizeof(USB_Descriptor_Device_t), .Type = DTYPE_Device}, + + .USBSpecification = VERSION_BCD(01.10), + .Class = CDC_CSCP_CDCClass, + .SubClass = CDC_CSCP_NoSpecificSubclass, + .Protocol = CDC_CSCP_NoSpecificProtocol, + + .Endpoint0Size = FIXED_CONTROL_ENDPOINT_SIZE, + + .VendorID = DEVICE_VID, + .ProductID = DEVICE_PID, + .ReleaseNumber = VERSION_BCD(00.01), + + .ManufacturerStrIndex = 0x02, + .ProductStrIndex = 0x01, + .SerialNumStrIndex = NO_DESCRIPTOR, + + .NumberOfConfigurations = FIXED_NUM_CONFIGURATIONS +}; + +/** Configuration descriptor structure. This descriptor, located in SRAM memory, describes the usage + * of the device in one of its supported configurations, including information about any device interfaces + * and endpoints. The descriptor is read out by the USB host during the enumeration process when selecting + * a configuration so that the host may correctly communicate with the USB device. + */ +const USB_Descriptor_Configuration_t ConfigurationDescriptor = +{ + .Config = + { + .Header = {.Size = sizeof(USB_Descriptor_Configuration_Header_t), .Type = DTYPE_Configuration}, + + .TotalConfigurationSize = sizeof(USB_Descriptor_Configuration_t), + .TotalInterfaces = 2, + + .ConfigurationNumber = 1, + .ConfigurationStrIndex = NO_DESCRIPTOR, + + .ConfigAttributes = USB_CONFIG_ATTR_BUSPOWERED, + + .MaxPowerConsumption = USB_CONFIG_POWER_MA(100) + }, + + .CDC_CCI_Interface = + { + .Header = {.Size = sizeof(USB_Descriptor_Interface_t), .Type = DTYPE_Interface}, + + .InterfaceNumber = 0, + .AlternateSetting = 0, + + .TotalEndpoints = 1, + + .Class = CDC_CSCP_CDCClass, + .SubClass = CDC_CSCP_ACMSubclass, + .Protocol = CDC_CSCP_ATCommandProtocol, + + .InterfaceStrIndex = NO_DESCRIPTOR + }, + + .CDC_Functional_Header = + { + .Header = {.Size = sizeof(USB_CDC_Descriptor_FunctionalHeader_t), .Type = DTYPE_CSInterface}, + .Subtype = 0x00, + + .CDCSpecification = VERSION_BCD(01.10), + }, + + .CDC_Functional_ACM = + { + .Header = {.Size = sizeof(USB_CDC_Descriptor_FunctionalACM_t), .Type = DTYPE_CSInterface}, + .Subtype = 0x02, + + .Capabilities = 0x04, + }, + + .CDC_Functional_Union = + { + .Header = {.Size = sizeof(USB_CDC_Descriptor_FunctionalUnion_t), .Type = DTYPE_CSInterface}, + .Subtype = 0x06, + + .MasterInterfaceNumber = 0, + .SlaveInterfaceNumber = 1, + }, + + .CDC_NotificationEndpoint = + { + .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint}, + + .EndpointAddress = (ENDPOINT_DIR_IN | CDC_NOTIFICATION_EPNUM), + .Attributes = (EP_TYPE_INTERRUPT | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA), + .EndpointSize = CDC_NOTIFICATION_EPSIZE, + .PollingIntervalMS = 0xFF + }, + + .CDC_DCI_Interface = + { + .Header = {.Size = sizeof(USB_Descriptor_Interface_t), .Type = DTYPE_Interface}, + + .InterfaceNumber = 1, + .AlternateSetting = 0, + + .TotalEndpoints = 2, + + .Class = CDC_CSCP_CDCDataClass, + .SubClass = CDC_CSCP_NoDataSubclass, + .Protocol = CDC_CSCP_NoDataProtocol, + + .InterfaceStrIndex = NO_DESCRIPTOR + }, + + .CDC_DataOutEndpoint = + { + .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint}, + + .EndpointAddress = (ENDPOINT_DIR_OUT | CDC_RX_EPNUM), + .Attributes = (EP_TYPE_BULK | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA), + .EndpointSize = CDC_TXRX_EPSIZE, + .PollingIntervalMS = 0x01 + }, + + .CDC_DataInEndpoint = + { + .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint}, + + .EndpointAddress = (ENDPOINT_DIR_IN | CDC_TX_EPNUM), + .Attributes = (EP_TYPE_BULK | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA), + .EndpointSize = CDC_TXRX_EPSIZE, + .PollingIntervalMS = 0x01 + } +}; + +/** Language descriptor structure. This descriptor, located in SRAM memory, is returned when the host requests + * the string descriptor with index 0 (the first index). It is actually an array of 16-bit integers, which indicate + * via the language ID table available at USB.org what languages the device supports for its string descriptors. + */ +const USB_Descriptor_String_t LanguageString = +{ + .Header = {.Size = USB_STRING_LEN(1), .Type = DTYPE_String}, + + .UnicodeString = {LANGUAGE_ID_ENG} +}; + +/** Product descriptor string. This is a Unicode string containing the product's details in human readable form, + * and is read out upon request by the host when the appropriate string ID is requested, listed in the Device + * Descriptor. + */ +const USB_Descriptor_String_t ProductString = +{ + .Header = {.Size = USB_STRING_LEN(19), .Type = DTYPE_String}, + + #if DEVICE_PID == 0x0036 + .UnicodeString = L"Arduino Leonardo" + #elif DEVICE_PID == 0x0037 + .UnicodeString = L"Arduino Micro " + #elif DEVICE_PID == 0x0038 + .UnicodeString = L"Robot Control Board" + #elif DEVICE_PID == 0x0039 + .UnicodeString = L"Robot Motor Board " + #elif DEVICE_PID == 0x003C + .UnicodeString = L"Arduino Esplora " + #else + .UnicodeString = L"USB IO board " + #endif +}; + +const USB_Descriptor_String_t ManufacturerString = +{ + .Header = {.Size = USB_STRING_LEN(11), .Type = DTYPE_String}, + + #if DEVICE_VID == 0x2341 + .UnicodeString = L"Arduino LLC" + #else + .UnicodeString = L"Unknown " + #endif +}; + +/** This function is called by the library when in device mode, and must be overridden (see LUFA library "USB Descriptors" + * documentation) by the application code so that the address and size of a requested descriptor can be given + * to the USB library. When the device receives a Get Descriptor request on the control endpoint, this function + * is called so that the descriptor details can be passed back and the appropriate descriptor sent back to the + * USB host. + */ +uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue, + const uint8_t wIndex, + const void** const DescriptorAddress) +{ + const uint8_t DescriptorType = (wValue >> 8); + const uint8_t DescriptorNumber = (wValue & 0xFF); + + const void* Address = NULL; + uint16_t Size = NO_DESCRIPTOR; + + switch (DescriptorType) + { + case DTYPE_Device: + Address = &DeviceDescriptor; + Size = sizeof(USB_Descriptor_Device_t); + break; + case DTYPE_Configuration: + Address = &ConfigurationDescriptor; + Size = sizeof(USB_Descriptor_Configuration_t); + break; + case DTYPE_String: + if (!(DescriptorNumber)) + { + Address = &LanguageString; + Size = LanguageString.Header.Size; + } + else if (DescriptorNumber == DeviceDescriptor.ProductStrIndex) + { + Address = &ProductString; + Size = ProductString.Header.Size; + } else if (DescriptorNumber == DeviceDescriptor.ManufacturerStrIndex) + { + Address = &ManufacturerString; + Size = ManufacturerString.Header.Size; + } + + break; + } + + *DescriptorAddress = Address; + return Size; +} + diff --git a/hardware/arduino/bootloaders/caterina-Arduino_Robot/Descriptors.h b/hardware/arduino/bootloaders/caterina-Arduino_Robot/Descriptors.h new file mode 100644 index 00000000000..94091aef046 --- /dev/null +++ b/hardware/arduino/bootloaders/caterina-Arduino_Robot/Descriptors.h @@ -0,0 +1,139 @@ +/* + LUFA Library + Copyright (C) Dean Camera, 2011. + + dean [at] fourwalledcubicle [dot] com + www.lufa-lib.org +*/ + +/* + Copyright 2011 Dean Camera (dean [at] fourwalledcubicle [dot] com) + + Permission to use, copy, modify, distribute, and sell this + software and its documentation for any purpose is hereby granted + without fee, provided that the above copyright notice appear in + all copies and that both that the copyright notice and this + permission notice and warranty disclaimer appear in supporting + documentation, and that the name of the author not be used in + advertising or publicity pertaining to distribution of the + software without specific, written prior permission. + + The author disclaim all warranties with regard to this + software, including all implied warranties of merchantability + and fitness. In no event shall the author be liable for any + special, indirect or consequential damages or any damages + whatsoever resulting from loss of use, data or profits, whether + in an action of contract, negligence or other tortious action, + arising out of or in connection with the use or performance of + this software. +*/ + +/** \file + * + * Header file for Descriptors.c. + */ + +#ifndef _DESCRIPTORS_H_ +#define _DESCRIPTORS_H_ + + /* Includes: */ + #include + + /* Macros: */ + #if defined(__AVR_AT90USB1287__) + #define AVR_SIGNATURE_1 0x1E + #define AVR_SIGNATURE_2 0x97 + #define AVR_SIGNATURE_3 0x82 + #elif defined(__AVR_AT90USB647__) + #define AVR_SIGNATURE_1 0x1E + #define AVR_SIGNATURE_2 0x96 + #define AVR_SIGNATURE_3 0x82 + #elif defined(__AVR_AT90USB1286__) + #define AVR_SIGNATURE_1 0x1E + #define AVR_SIGNATURE_2 0x97 + #define AVR_SIGNATURE_3 0x82 + #elif defined(__AVR_AT90USB646__) + #define AVR_SIGNATURE_1 0x1E + #define AVR_SIGNATURE_2 0x96 + #define AVR_SIGNATURE_3 0x82 + #elif defined(__AVR_ATmega32U6__) + #define AVR_SIGNATURE_1 0x1E + #define AVR_SIGNATURE_2 0x95 + #define AVR_SIGNATURE_3 0x88 + #elif defined(__AVR_ATmega32U4__) + #define AVR_SIGNATURE_1 0x1E + #define AVR_SIGNATURE_2 0x95 + #define AVR_SIGNATURE_3 0x87 + #elif defined(__AVR_ATmega16U4__) + #define AVR_SIGNATURE_1 0x1E + #define AVR_SIGNATURE_2 0x94 + #define AVR_SIGNATURE_3 0x88 + #elif defined(__AVR_ATmega32U2__) + #define AVR_SIGNATURE_1 0x1E + #define AVR_SIGNATURE_2 0x95 + #define AVR_SIGNATURE_3 0x8A + #elif defined(__AVR_ATmega16U2__) + #define AVR_SIGNATURE_1 0x1E + #define AVR_SIGNATURE_2 0x94 + #define AVR_SIGNATURE_3 0x89 + #elif defined(__AVR_AT90USB162__) + #define AVR_SIGNATURE_1 0x1E + #define AVR_SIGNATURE_2 0x94 + #define AVR_SIGNATURE_3 0x82 + #elif defined(__AVR_ATmega8U2__) + #define AVR_SIGNATURE_1 0x1E + #define AVR_SIGNATURE_2 0x93 + #define AVR_SIGNATURE_3 0x89 + #elif defined(__AVR_AT90USB82__) + #define AVR_SIGNATURE_1 0x1E + #define AVR_SIGNATURE_2 0x94 + #define AVR_SIGNATURE_3 0x82 + #else + #error The selected AVR part is not currently supported by this bootloader. + #endif + + /** Endpoint number for the CDC control interface event notification endpoint. */ + #define CDC_NOTIFICATION_EPNUM 2 + + /** Endpoint number for the CDC data interface TX (data IN) endpoint. */ + #define CDC_TX_EPNUM 3 + + /** Endpoint number for the CDC data interface RX (data OUT) endpoint. */ + #define CDC_RX_EPNUM 4 + + /** Size of the CDC data interface TX and RX data endpoint banks, in bytes. */ + #define CDC_TXRX_EPSIZE 16 + + /** Size of the CDC control interface notification endpoint bank, in bytes. */ + #define CDC_NOTIFICATION_EPSIZE 8 + + /* Type Defines: */ + /** Type define for the device configuration descriptor structure. This must be defined in the + * application code, as the configuration descriptor contains several sub-descriptors which + * vary between devices, and which describe the device's usage to the host. + */ + typedef struct + { + USB_Descriptor_Configuration_Header_t Config; + + // CDC Control Interface + USB_Descriptor_Interface_t CDC_CCI_Interface; + USB_CDC_Descriptor_FunctionalHeader_t CDC_Functional_Header; + USB_CDC_Descriptor_FunctionalACM_t CDC_Functional_ACM; + USB_CDC_Descriptor_FunctionalUnion_t CDC_Functional_Union; + USB_Descriptor_Endpoint_t CDC_NotificationEndpoint; + + // CDC Data Interface + USB_Descriptor_Interface_t CDC_DCI_Interface; + USB_Descriptor_Endpoint_t CDC_DataOutEndpoint; + USB_Descriptor_Endpoint_t CDC_DataInEndpoint; + } USB_Descriptor_Configuration_t; + + /* Function Prototypes: */ + uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue, + const uint8_t wIndex, + const void** const DescriptorAddress) + ATTR_WARN_UNUSED_RESULT ATTR_NON_NULL_PTR_ARG(3); + +#endif + diff --git a/hardware/arduino/bootloaders/caterina-Arduino_Robot/Makefile b/hardware/arduino/bootloaders/caterina-Arduino_Robot/Makefile new file mode 100644 index 00000000000..af9990e962d --- /dev/null +++ b/hardware/arduino/bootloaders/caterina-Arduino_Robot/Makefile @@ -0,0 +1,738 @@ +# Hey Emacs, this is a -*- makefile -*- +#---------------------------------------------------------------------------- +# WinAVR Makefile Template written by Eric B. Weddington, J�rg Wunsch, et al. +# >> Modified for use with the LUFA project. << +# +# Released to the Public Domain +# +# Additional material for this makefile was written by: +# Peter Fleury +# Tim Henigan +# Colin O'Flynn +# Reiner Patommel +# Markus Pfaff +# Sander Pool +# Frederik Rouleau +# Carlos Lamas +# Dean Camera +# Opendous Inc. +# Denver Gingerich +# +#---------------------------------------------------------------------------- +# On command line: +# +# make all = Make software. +# +# make clean = Clean out built project files. +# +# make coff = Convert ELF to AVR COFF. +# +# make extcoff = Convert ELF to AVR Extended COFF. +# +# make program = Download the hex file to the device, using avrdude. +# Please customize the avrdude settings below first! +# +# make doxygen = Generate DoxyGen documentation for the project (must have +# DoxyGen installed) +# +# make debug = Start either simulavr or avarice as specified for debugging, +# with avr-gdb or avr-insight as the front end for debugging. +# +# make filename.s = Just compile filename.c into the assembler code only. +# +# make filename.i = Create a preprocessed source file for use in submitting +# bug reports to the GCC project. +# +# To rebuild project do "make clean" then "make all". +#---------------------------------------------------------------------------- + +# USB vendor ID (VID) +# reuse of this VID by others is forbidden by USB-IF +# official Arduino LLC VID +VID = 0x2341 + + +# USB product ID (PID) +# official Leonardo PID +# PID = 0x0036 +# official Micro PID +# PID = 0x0037 +# official Arduino Robot Control Board PID +PID = 0x0038 +# official Arduino Robot Motor Board PID +# PID = 0x0039 +# official Esplora PID +# PID = 0x003C + +# MCU name +MCU = atmega32u4 + + +# Target architecture (see library "Board Types" documentation). +ARCH = AVR8 + + +# Target board (see library "Board Types" documentation, NONE for projects not requiring +# LUFA board drivers). If USER is selected, put custom board drivers in a directory called +# "Board" inside the application directory. +BOARD = USER + + +# Processor frequency. +# This will define a symbol, F_CPU, in all source code files equal to the +# processor frequency in Hz. You can then use this symbol in your source code to +# calculate timings. Do NOT tack on a 'UL' at the end, this will be done +# automatically to create a 32-bit value in your source code. +# +# This will be an integer division of F_USB below, as it is sourced by +# F_USB after it has run through any CPU prescalers. Note that this value +# does not *change* the processor frequency - it should merely be updated to +# reflect the processor speed set externally so that the code can use accurate +# software delays. +F_CPU = 16000000 + + +# Input clock frequency. +# This will define a symbol, F_USB, in all source code files equal to the +# input clock frequency (before any prescaling is performed) in Hz. This value may +# differ from F_CPU if prescaling is used on the latter, and is required as the +# raw input clock is fed directly to the PLL sections of the AVR for high speed +# clock generation for the USB and other AVR subsections. Do NOT tack on a 'UL' +# at the end, this will be done automatically to create a 32-bit value in your +# source code. +# +# If no clock division is performed on the input clock inside the AVR (via the +# CPU clock adjust registers or the clock division fuses), this will be equal to F_CPU. +F_USB = $(F_CPU) + + +# Starting byte address of the bootloader, as a byte address - computed via the formula +# BOOT_START = ((FLASH_SIZE_KB - BOOT_SECTION_SIZE_KB) * 1024) +# +# Note that the bootloader size and start address given in AVRStudio is in words and not +# bytes, and so will need to be doubled to obtain the byte address needed by AVR-GCC. +FLASH_SIZE_KB = 32 +BOOT_SECTION_SIZE_KB = 4 +BOOT_START = 0x$(shell echo "obase=16; ($(FLASH_SIZE_KB) - $(BOOT_SECTION_SIZE_KB)) * 1024" | bc) + + +# Output format. (can be srec, ihex, binary) +FORMAT = ihex + + +# Target file name (without extension). +TARGET = Caterina + + +# Object files directory +# To put object files in current directory, use a dot (.), do NOT make +# this an empty or blank macro! +OBJDIR = . + + +# Path to the LUFA library +LUFA_PATH = LUFA-111009 + + +# LUFA library compile-time options and predefined tokens +LUFA_OPTS = -D USB_DEVICE_ONLY +LUFA_OPTS += -D DEVICE_STATE_AS_GPIOR=0 +LUFA_OPTS += -D ORDERED_EP_CONFIG +LUFA_OPTS += -D FIXED_CONTROL_ENDPOINT_SIZE=8 +LUFA_OPTS += -D FIXED_NUM_CONFIGURATIONS=1 +LUFA_OPTS += -D USE_RAM_DESCRIPTORS +LUFA_OPTS += -D USE_STATIC_OPTIONS="(USB_DEVICE_OPT_FULLSPEED | USB_OPT_REG_ENABLED | USB_OPT_AUTO_PLL)" +LUFA_OPTS += -D NO_INTERNAL_SERIAL +LUFA_OPTS += -D NO_DEVICE_SELF_POWER +LUFA_OPTS += -D NO_DEVICE_REMOTE_WAKEUP +LUFA_OPTS += -D NO_SOF_EVENTS + +#LUFA_OPTS += -D NO_BLOCK_SUPPORT +#LUFA_OPTS += -D NO_EEPROM_BYTE_SUPPORT +#LUFA_OPTS += -D NO_FLASH_BYTE_SUPPORT +LUFA_OPTS += -D NO_LOCK_BYTE_WRITE_SUPPORT + + +# Create the LUFA source path variables by including the LUFA root makefile +include $(LUFA_PATH)/LUFA/makefile + + +# List C source files here. (C dependencies are automatically generated.) +SRC = $(TARGET).c \ + Descriptors.c \ + $(LUFA_SRC_USB) \ + + +# List C++ source files here. (C dependencies are automatically generated.) +CPPSRC = + + +# List Assembler source files here. +# Make them always end in a capital .S. Files ending in a lowercase .s +# will not be considered source files but generated files (assembler +# output from the compiler), and will be deleted upon "make clean"! +# Even though the DOS/Win* filesystem matches both .s and .S the same, +# it will preserve the spelling of the filenames, and gcc itself does +# care about how the name is spelled on its command-line. +ASRC = + + +# Optimization level, can be [0, 1, 2, 3, s]. +# 0 = turn off optimization. s = optimize for size. +# (Note: 3 is not always the best optimization level. See avr-libc FAQ.) +OPT = s + + +# Debugging format. +# Native formats for AVR-GCC's -g are dwarf-2 [default] or stabs. +# AVR Studio 4.10 requires dwarf-2. +# AVR [Extended] COFF format requires stabs, plus an avr-objcopy run. +DEBUG = dwarf-2 + + +# List any extra directories to look for include files here. +# Each directory must be seperated by a space. +# Use forward slashes for directory separators. +# For a directory that has spaces, enclose it in quotes. +EXTRAINCDIRS = $(LUFA_PATH)/ + + +# Compiler flag to set the C Standard level. +# c89 = "ANSI" C +# gnu89 = c89 plus GCC extensions +# c99 = ISO C99 standard (not yet fully implemented) +# gnu99 = c99 plus GCC extensions +CSTANDARD = -std=c99 + + +# Place -D or -U options here for C sources +CDEFS = -DF_CPU=$(F_CPU)UL +CDEFS += -DF_USB=$(F_USB)UL +CDEFS += -DBOARD=BOARD_$(BOARD) -DARCH=ARCH_$(ARCH) +CDEFS += -DBOOT_START_ADDR=$(BOOT_START)UL +CDEFS += -DDEVICE_VID=$(VID)UL +CDEFS += -DDEVICE_PID=$(PID)UL +CDEFS += $(LUFA_OPTS) + + +# Place -D or -U options here for ASM sources +ADEFS = -DF_CPU=$(F_CPU) +ADEFS += -DF_USB=$(F_USB)UL +ADEFS += -DBOARD=BOARD_$(BOARD) +ADEFS += -DBOOT_START_ADDR=$(BOOT_START)UL +ADEFS += $(LUFA_OPTS) + + +# Place -D or -U options here for C++ sources +CPPDEFS = -DF_CPU=$(F_CPU)UL +CPPDEFS += -DF_USB=$(F_USB)UL +CPPDEFS += -DBOARD=BOARD_$(BOARD) +CPPDEFS += -DBOOT_START_ADDR=$(BOOT_START)UL +CPPDEFS += $(LUFA_OPTS) +#CPPDEFS += -D__STDC_LIMIT_MACROS +#CPPDEFS += -D__STDC_CONSTANT_MACROS + + + +#---------------- Compiler Options C ---------------- +# -g*: generate debugging information +# -O*: optimization level +# -f...: tuning, see GCC manual and avr-libc documentation +# -Wall...: warning level +# -Wa,...: tell GCC to pass this to the assembler. +# -adhlns...: create assembler listing +CFLAGS = -g$(DEBUG) +CFLAGS += $(CDEFS) +CFLAGS += -O$(OPT) +CFLAGS += -funsigned-char +CFLAGS += -funsigned-bitfields +CFLAGS += -ffunction-sections +CFLAGS += -fno-inline-small-functions +CFLAGS += -fpack-struct +CFLAGS += -fshort-enums +CFLAGS += -fno-strict-aliasing +CFLAGS += -Wall +CFLAGS += -Wstrict-prototypes +#CFLAGS += -mshort-calls +#CFLAGS += -fno-unit-at-a-time +#CFLAGS += -Wundef +#CFLAGS += -Wunreachable-code +#CFLAGS += -Wsign-compare +CFLAGS += -Wa,-adhlns=$(<:%.c=$(OBJDIR)/%.lst) +CFLAGS += $(patsubst %,-I%,$(EXTRAINCDIRS)) +CFLAGS += $(CSTANDARD) + + +#---------------- Compiler Options C++ ---------------- +# -g*: generate debugging information +# -O*: optimization level +# -f...: tuning, see GCC manual and avr-libc documentation +# -Wall...: warning level +# -Wa,...: tell GCC to pass this to the assembler. +# -adhlns...: create assembler listing +CPPFLAGS = -g$(DEBUG) +CPPFLAGS += $(CPPDEFS) +CPPFLAGS += -O$(OPT) +CPPFLAGS += -funsigned-char +CPPFLAGS += -funsigned-bitfields +CPPFLAGS += -fpack-struct +CPPFLAGS += -fshort-enums +CPPFLAGS += -fno-exceptions +CPPFLAGS += -Wall +CPPFLAGS += -Wundef +#CPPFLAGS += -mshort-calls +#CPPFLAGS += -fno-unit-at-a-time +#CPPFLAGS += -Wstrict-prototypes +#CPPFLAGS += -Wunreachable-code +#CPPFLAGS += -Wsign-compare +CPPFLAGS += -Wa,-adhlns=$(<:%.cpp=$(OBJDIR)/%.lst) +CPPFLAGS += $(patsubst %,-I%,$(EXTRAINCDIRS)) +#CPPFLAGS += $(CSTANDARD) + + +#---------------- Assembler Options ---------------- +# -Wa,...: tell GCC to pass this to the assembler. +# -adhlns: create listing +# -gstabs: have the assembler create line number information; note that +# for use in COFF files, additional information about filenames +# and function names needs to be present in the assembler source +# files -- see avr-libc docs [FIXME: not yet described there] +# -listing-cont-lines: Sets the maximum number of continuation lines of hex +# dump that will be displayed for a given single line of source input. +ASFLAGS = $(ADEFS) -Wa,-adhlns=$(<:%.S=$(OBJDIR)/%.lst),-gstabs,--listing-cont-lines=100 + + +#---------------- Library Options ---------------- +# Minimalistic printf version +PRINTF_LIB_MIN = -Wl,-u,vfprintf -lprintf_min + +# Floating point printf version (requires MATH_LIB = -lm below) +PRINTF_LIB_FLOAT = -Wl,-u,vfprintf -lprintf_flt + +# If this is left blank, then it will use the Standard printf version. +PRINTF_LIB = +#PRINTF_LIB = $(PRINTF_LIB_MIN) +#PRINTF_LIB = $(PRINTF_LIB_FLOAT) + + +# Minimalistic scanf version +SCANF_LIB_MIN = -Wl,-u,vfscanf -lscanf_min + +# Floating point + %[ scanf version (requires MATH_LIB = -lm below) +SCANF_LIB_FLOAT = -Wl,-u,vfscanf -lscanf_flt + +# If this is left blank, then it will use the Standard scanf version. +SCANF_LIB = +#SCANF_LIB = $(SCANF_LIB_MIN) +#SCANF_LIB = $(SCANF_LIB_FLOAT) + + +MATH_LIB = -lm + + +# List any extra directories to look for libraries here. +# Each directory must be seperated by a space. +# Use forward slashes for directory separators. +# For a directory that has spaces, enclose it in quotes. +EXTRALIBDIRS = + + + +#---------------- External Memory Options ---------------- + +# 64 KB of external RAM, starting after internal RAM (ATmega128!), +# used for variables (.data/.bss) and heap (malloc()). +#EXTMEMOPTS = -Wl,-Tdata=0x801100,--defsym=__heap_end=0x80ffff + +# 64 KB of external RAM, starting after internal RAM (ATmega128!), +# only used for heap (malloc()). +#EXTMEMOPTS = -Wl,--section-start,.data=0x801100,--defsym=__heap_end=0x80ffff + +EXTMEMOPTS = + + + +#---------------- Linker Options ---------------- +# -Wl,...: tell GCC to pass this to linker. +# -Map: create map file +# --cref: add cross reference to map file +LDFLAGS = -Wl,-Map=$(TARGET).map,--cref +LDFLAGS += -Wl,--section-start=.text=$(BOOT_START) +LDFLAGS += -Wl,--relax +LDFLAGS += -Wl,--gc-sections +LDFLAGS += $(EXTMEMOPTS) +LDFLAGS += $(patsubst %,-L%,$(EXTRALIBDIRS)) +LDFLAGS += $(PRINTF_LIB) $(SCANF_LIB) $(MATH_LIB) +#LDFLAGS += -T linker_script.x + + + +#---------------- Programming Options (avrdude) ---------------- + +# Programming hardware +# Type: avrdude -c ? +# to get a full listing. +# +#AVRDUDE_PROGRAMMER = avrispmkII +AVRDUDE_PROGRAMMER = usbtiny + +# com1 = serial port. Use lpt1 to connect to parallel port. +AVRDUDE_PORT = usb + +AVRDUDE_WRITE_FLASH = -U flash:w:$(TARGET).hex +#AVRDUDE_WRITE_EEPROM = -U eeprom:w:$(TARGET).eep + + +# Uncomment the following if you want avrdude's erase cycle counter. +# Note that this counter needs to be initialized first using -Yn, +# see avrdude manual. +#AVRDUDE_ERASE_COUNTER = -y + +# Uncomment the following if you do /not/ wish a verification to be +# performed after programming the device. +#AVRDUDE_NO_VERIFY = -V + +# Increase verbosity level. Please use this when submitting bug +# reports about avrdude. See +# to submit bug reports. +#AVRDUDE_VERBOSE = -v -v + +AVRDUDE_FLAGS = -p $(MCU) -P $(AVRDUDE_PORT) -c $(AVRDUDE_PROGRAMMER) +AVRDUDE_FLAGS += $(AVRDUDE_NO_VERIFY) +AVRDUDE_FLAGS += $(AVRDUDE_VERBOSE) +AVRDUDE_FLAGS += $(AVRDUDE_ERASE_COUNTER) + + + +#---------------- Debugging Options ---------------- + +# For simulavr only - target MCU frequency. +DEBUG_MFREQ = $(F_CPU) + +# Set the DEBUG_UI to either gdb or insight. +# DEBUG_UI = gdb +DEBUG_UI = insight + +# Set the debugging back-end to either avarice, simulavr. +DEBUG_BACKEND = avarice +#DEBUG_BACKEND = simulavr + +# GDB Init Filename. +GDBINIT_FILE = __avr_gdbinit + +# When using avarice settings for the JTAG +JTAG_DEV = /dev/com1 + +# Debugging port used to communicate between GDB / avarice / simulavr. +DEBUG_PORT = 4242 + +# Debugging host used to communicate between GDB / avarice / simulavr, normally +# just set to localhost unless doing some sort of crazy debugging when +# avarice is running on a different computer. +DEBUG_HOST = localhost + + + +#============================================================================ + + +# Define programs and commands. +SHELL = sh +CC = avr-gcc +OBJCOPY = avr-objcopy +OBJDUMP = avr-objdump +SIZE = avr-size +AR = avr-ar rcs +NM = avr-nm +#AVRDUDE = /Applications/avrdude -C /Applications/avrdude.conf -B 1 +AVRDUDE = /home/david/tmp/Arduino-master/build/linux/dist/tools/avrdude -B 1 -C /home/david/tmp/Arduino-master/build/linux/dist/tools/avrdude.conf +REMOVE = rm -f +REMOVEDIR = rm -rf +COPY = cp +WINSHELL = cmd + + +# Define Messages +# English +MSG_ERRORS_NONE = Errors: none +MSG_BEGIN = -------- begin -------- +MSG_END = -------- end -------- +MSG_SIZE_BEFORE = Size before: +MSG_SIZE_AFTER = Size after: +MSG_COFF = Converting to AVR COFF: +MSG_EXTENDED_COFF = Converting to AVR Extended COFF: +MSG_FLASH = Creating load file for Flash: +MSG_EEPROM = Creating load file for EEPROM: +MSG_EXTENDED_LISTING = Creating Extended Listing: +MSG_SYMBOL_TABLE = Creating Symbol Table: +MSG_LINKING = Linking: +MSG_COMPILING = Compiling C: +MSG_COMPILING_CPP = Compiling C++: +MSG_ASSEMBLING = Assembling: +MSG_CLEANING = Cleaning project: +MSG_CREATING_LIBRARY = Creating library: + + + + +# Define all object files. +OBJ = $(SRC:%.c=$(OBJDIR)/%.o) $(CPPSRC:%.cpp=$(OBJDIR)/%.o) $(ASRC:%.S=$(OBJDIR)/%.o) + +# Define all listing files. +LST = $(SRC:%.c=$(OBJDIR)/%.lst) $(CPPSRC:%.cpp=$(OBJDIR)/%.lst) $(ASRC:%.S=$(OBJDIR)/%.lst) + + +# Compiler flags to generate dependency files. +GENDEPFLAGS = -MMD -MP -MF .dep/$(@F).d + + +# Combine all necessary flags and optional flags. +# Add target processor to flags. +ALL_CFLAGS = -mmcu=$(MCU) -I. $(CFLAGS) $(GENDEPFLAGS) +ALL_CPPFLAGS = -mmcu=$(MCU) -I. -x c++ $(CPPFLAGS) $(GENDEPFLAGS) +ALL_ASFLAGS = -mmcu=$(MCU) -I. -x assembler-with-cpp $(ASFLAGS) + + + + + +# Default target. +all: begin gccversion sizebefore build sizeafter end + +# Change the build target to build a HEX file or a library. +build: elf hex eep lss sym +#build: lib + + +elf: $(TARGET).elf +hex: $(TARGET).hex +eep: $(TARGET).eep +lss: $(TARGET).lss +sym: $(TARGET).sym +LIBNAME=lib$(TARGET).a +lib: $(LIBNAME) + + + +# Eye candy. +# AVR Studio 3.x does not check make's exit code but relies on +# the following magic strings to be generated by the compile job. +begin: + @echo + @echo $(MSG_BEGIN) + +end: + @echo $(MSG_END) + @echo + + +# Display size of file. +HEXSIZE = $(SIZE) --target=$(FORMAT) $(TARGET).hex +ELFSIZE = $(SIZE) $(MCU_FLAG) $(FORMAT_FLAG) $(TARGET).elf +MCU_FLAG = $(shell $(SIZE) --help | grep -- --mcu > /dev/null && echo --mcu=$(MCU) ) +FORMAT_FLAG = $(shell $(SIZE) --help | grep -- --format=.*avr > /dev/null && echo --format=avr ) + + +sizebefore: + @if test -f $(TARGET).elf; then echo; echo $(MSG_SIZE_BEFORE); $(ELFSIZE); \ + 2>/dev/null; echo; fi + +sizeafter: + @if test -f $(TARGET).elf; then echo; echo $(MSG_SIZE_AFTER); $(ELFSIZE); \ + 2>/dev/null; echo; fi + + + +# Display compiler version information. +gccversion : + @$(CC) --version + + +# Program the device. +program: $(TARGET).hex $(TARGET).eep + $(AVRDUDE) $(AVRDUDE_FLAGS) $(AVRDUDE_WRITE_FLASH) $(AVRDUDE_WRITE_EEPROM) + + +# Generate avr-gdb config/init file which does the following: +# define the reset signal, load the target file, connect to target, and set +# a breakpoint at main(). +gdb-config: + @$(REMOVE) $(GDBINIT_FILE) + @echo define reset >> $(GDBINIT_FILE) + @echo SIGNAL SIGHUP >> $(GDBINIT_FILE) + @echo end >> $(GDBINIT_FILE) + @echo file $(TARGET).elf >> $(GDBINIT_FILE) + @echo target remote $(DEBUG_HOST):$(DEBUG_PORT) >> $(GDBINIT_FILE) +ifeq ($(DEBUG_BACKEND),simulavr) + @echo load >> $(GDBINIT_FILE) +endif + @echo break main >> $(GDBINIT_FILE) + +debug: gdb-config $(TARGET).elf +ifeq ($(DEBUG_BACKEND), avarice) + @echo Starting AVaRICE - Press enter when "waiting to connect" message displays. + @$(WINSHELL) /c start avarice --jtag $(JTAG_DEV) --erase --program --file \ + $(TARGET).elf $(DEBUG_HOST):$(DEBUG_PORT) + @$(WINSHELL) /c pause + +else + @$(WINSHELL) /c start simulavr --gdbserver --device $(MCU) --clock-freq \ + $(DEBUG_MFREQ) --port $(DEBUG_PORT) +endif + @$(WINSHELL) /c start avr-$(DEBUG_UI) --command=$(GDBINIT_FILE) + + + + +# Convert ELF to COFF for use in debugging / simulating in AVR Studio or VMLAB. +COFFCONVERT = $(OBJCOPY) --debugging +COFFCONVERT += --change-section-address .data-0x800000 +COFFCONVERT += --change-section-address .bss-0x800000 +COFFCONVERT += --change-section-address .noinit-0x800000 +COFFCONVERT += --change-section-address .eeprom-0x810000 + + + +coff: $(TARGET).elf + @echo + @echo $(MSG_COFF) $(TARGET).cof + $(COFFCONVERT) -O coff-avr $< $(TARGET).cof + + +extcoff: $(TARGET).elf + @echo + @echo $(MSG_EXTENDED_COFF) $(TARGET).cof + $(COFFCONVERT) -O coff-ext-avr $< $(TARGET).cof + + + +# Create final output files (.hex, .eep) from ELF output file. +%.hex: %.elf + @echo + @echo $(MSG_FLASH) $@ + $(OBJCOPY) -O $(FORMAT) -R .eeprom -R .fuse -R .lock $< $@ + +%.eep: %.elf + @echo + @echo $(MSG_EEPROM) $@ + -$(OBJCOPY) -j .eeprom --set-section-flags=.eeprom="alloc,load" \ + --change-section-lma .eeprom=0 --no-change-warnings -O $(FORMAT) $< $@ || exit 0 + +# Create extended listing file from ELF output file. +%.lss: %.elf + @echo + @echo $(MSG_EXTENDED_LISTING) $@ + $(OBJDUMP) -h -S -z $< > $@ + +# Create a symbol table from ELF output file. +%.sym: %.elf + @echo + @echo $(MSG_SYMBOL_TABLE) $@ + $(NM) -n $< > $@ + + + +# Create library from object files. +.SECONDARY : $(TARGET).a +.PRECIOUS : $(OBJ) +%.a: $(OBJ) + @echo + @echo $(MSG_CREATING_LIBRARY) $@ + $(AR) $@ $(OBJ) + + +# Link: create ELF output file from object files. +.SECONDARY : $(TARGET).elf +.PRECIOUS : $(OBJ) +%.elf: $(OBJ) + @echo + @echo $(MSG_LINKING) $@ + $(CC) $(ALL_CFLAGS) $^ --output $@ $(LDFLAGS) + + +# Compile: create object files from C source files. +$(OBJDIR)/%.o : %.c + @echo + @echo $(MSG_COMPILING) $< + $(CC) -c $(ALL_CFLAGS) $< -o $@ + + +# Compile: create object files from C++ source files. +$(OBJDIR)/%.o : %.cpp + @echo + @echo $(MSG_COMPILING_CPP) $< + $(CC) -c $(ALL_CPPFLAGS) $< -o $@ + + +# Compile: create assembler files from C source files. +%.s : %.c + $(CC) -S $(ALL_CFLAGS) $< -o $@ + + +# Compile: create assembler files from C++ source files. +%.s : %.cpp + $(CC) -S $(ALL_CPPFLAGS) $< -o $@ + + +# Assemble: create object files from assembler source files. +$(OBJDIR)/%.o : %.S + @echo + @echo $(MSG_ASSEMBLING) $< + $(CC) -c $(ALL_ASFLAGS) $< -o $@ + + +# Create preprocessed source for use in sending a bug report. +%.i : %.c + $(CC) -E -mmcu=$(MCU) -I. $(CFLAGS) $< -o $@ + + +# Target: clean project. +clean: begin clean_list end + +clean_list : + @echo + @echo $(MSG_CLEANING) + $(REMOVE) $(TARGET).hex + $(REMOVE) $(TARGET).eep + $(REMOVE) $(TARGET).cof + $(REMOVE) $(TARGET).elf + $(REMOVE) $(TARGET).map + $(REMOVE) $(TARGET).sym + $(REMOVE) $(TARGET).lss + $(REMOVE) $(SRC:%.c=$(OBJDIR)/%.o) $(CPPSRC:%.cpp=$(OBJDIR)/%.o) $(ASRC:%.S=$(OBJDIR)/%.o) + $(REMOVE) $(SRC:%.c=$(OBJDIR)/%.lst) $(CPPSRC:%.cpp=$(OBJDIR)/%.lst) $(ASRC:%.S=$(OBJDIR)/%.lst) + $(REMOVE) $(SRC:.c=.s) + $(REMOVE) $(SRC:.c=.d) + $(REMOVE) $(SRC:.c=.i) + $(REMOVEDIR) .dep + +doxygen: + @echo Generating Project Documentation \($(TARGET)\)... + @doxygen Doxygen.conf + @echo Documentation Generation Complete. + +clean_doxygen: + rm -rf Documentation + +checksource: + @for f in $(SRC) $(CPPSRC) $(ASRC); do \ + if [ -f $$f ]; then \ + echo "Found Source File: $$f" ; \ + else \ + echo "Source File Not Found: $$f" ; \ + fi; done + + +# Create object files directory +$(shell mkdir $(OBJDIR) 2>/dev/null) + + +# Include the dependency files. +-include $(shell mkdir .dep 2>/dev/null) $(wildcard .dep/*) + + +# Listing of phony targets. +.PHONY : all begin finish end sizebefore sizeafter gccversion \ +build elf hex eep lss sym coff extcoff doxygen clean \ +clean_list clean_doxygen program debug gdb-config checksource + diff --git a/hardware/arduino/bootloaders/caterina-Arduino_Robot/README.md b/hardware/arduino/bootloaders/caterina-Arduino_Robot/README.md new file mode 100644 index 00000000000..08235e0a41c --- /dev/null +++ b/hardware/arduino/bootloaders/caterina-Arduino_Robot/README.md @@ -0,0 +1,27 @@ +Building the bootloader for the Arduino Robot +============================================= + +The Arduino Robot has two boards featuring the atmega32U4 processor from Atmel. Each one of them is identified as a different board at the USB level and has a different bootloader. + +The Arduino Robot Control board has the USB identifier 0x0038. This is the value configured by default in the Makefile. + +The Arduino Robot Motor board has the USB identifier 0x0039. If you want to compile/upload this version of the bootloader, you will have to edit the Makefile, comment away the like dedicated to the PID and uncomment the one that configures such variable accordingly. + +The general conditions for using these bootloaders require downloading a specific version of LUFA as explained here: + +1. Download the LUFA-111009 file (http://fourwalledcubicle.com/blog/2011/10/lufa-111009-released/). +2. Extract that file directly to the Caterina-Arduino_Robot bootloader directory. +3. Open a command prompt in the Caterina-Arduino_Robot bootloader directory. +4. Type 'make'. +5. Enjoy! + +Programming the bootloader for one of the Arduino Robot boards +1. Open a command prompt in the Caterina-Arduino_Robot folder. +2. Connect your programmer- use a 2x3 .1" header, pressed against the programming vias. +3. Edit the make file for it to include the right programmer (e.g. in my lab I have AVRMKII and USBTINY ISP) +4. Type 'make program' into the command prompt. + +Differences between this bootoloader and the standard one for Leonardo boards +============================================================================= + +This bootloader is different from the one on the standard Leonardo boards. To enter the bootloader, you need to double click the reset button. You need to click twice in less that 3/4 of a second (easy uh?). This bootloader, designed in the first place for the LilypadUSB, seems to be optimal for situations when users are e.g. using their robots in soccer competitions where they make direct manipulation of the board as it runs. diff --git a/hardware/arduino/cores/arduino/Arduino.h b/hardware/arduino/cores/arduino/Arduino.h index b265825894a..93a3525d655 100755 --- a/hardware/arduino/cores/arduino/Arduino.h +++ b/hardware/arduino/cores/arduino/Arduino.h @@ -1,3 +1,22 @@ +/* + Arduino.h - Main include file for the Arduino SDK + Copyright (c) 2005-2013 Arduino Team. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + #ifndef Arduino_h #define Arduino_h @@ -46,7 +65,7 @@ extern "C"{ #define EXTERNAL 1 #define INTERNAL 2 #else -#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega644P__) +#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega644__) || defined(__AVR_ATmega644A__) || defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644PA__) #define INTERNAL1V1 2 #define INTERNAL2V56 3 #else diff --git a/hardware/arduino/cores/arduino/CDC.cpp b/hardware/arduino/cores/arduino/CDC.cpp index 701e48398fc..e1e859d18c4 100644 --- a/hardware/arduino/cores/arduino/CDC.cpp +++ b/hardware/arduino/cores/arduino/CDC.cpp @@ -130,7 +130,11 @@ bool WEAK CDC_Setup(Setup& setup) int _serialPeek = -1; -void Serial_::begin(uint16_t baud_count) +void Serial_::begin(unsigned long baud_count) +{ +} + +void Serial_::begin(unsigned long baud_count, byte config) { } diff --git a/hardware/arduino/cores/arduino/Client.h b/hardware/arduino/cores/arduino/Client.h index ea134838a2c..b8e5d935f2a 100644 --- a/hardware/arduino/cores/arduino/Client.h +++ b/hardware/arduino/cores/arduino/Client.h @@ -1,3 +1,22 @@ +/* + Client.h - Base class that provides Client + Copyright (c) 2011 Adrian McEwen. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + #ifndef client_h #define client_h #include "Print.h" diff --git a/hardware/arduino/cores/arduino/IPAddress.cpp b/hardware/arduino/cores/arduino/IPAddress.cpp index fe3deb77a2e..353217237cd 100644 --- a/hardware/arduino/cores/arduino/IPAddress.cpp +++ b/hardware/arduino/cores/arduino/IPAddress.cpp @@ -1,3 +1,21 @@ +/* + IPAddress.cpp - Base class that provides IPAddress + Copyright (c) 2011 Adrian McEwen. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ #include #include diff --git a/hardware/arduino/cores/arduino/IPAddress.h b/hardware/arduino/cores/arduino/IPAddress.h index 2585aec0e48..c2dd7e559d6 100644 --- a/hardware/arduino/cores/arduino/IPAddress.h +++ b/hardware/arduino/cores/arduino/IPAddress.h @@ -1,27 +1,21 @@ /* - * - * MIT License: - * Copyright (c) 2011 Adrian McEwen - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - * adrianm@mcqn.com 1/1/2011 - */ + IPAddress.h - Base class that provides IPAddress + Copyright (c) 2011 Adrian McEwen. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ #ifndef IPAddress_h #define IPAddress_h diff --git a/hardware/arduino/cores/arduino/Server.h b/hardware/arduino/cores/arduino/Server.h index 9674c762696..77c415cce06 100644 --- a/hardware/arduino/cores/arduino/Server.h +++ b/hardware/arduino/cores/arduino/Server.h @@ -1,3 +1,22 @@ +/* + Server.h - Base class that provides Server + Copyright (c) 2011 Adrian McEwen. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + #ifndef server_h #define server_h diff --git a/hardware/arduino/cores/arduino/Stream.h b/hardware/arduino/cores/arduino/Stream.h index 58bbf752f33..007b4bc66c7 100644 --- a/hardware/arduino/cores/arduino/Stream.h +++ b/hardware/arduino/cores/arduino/Stream.h @@ -37,7 +37,7 @@ readBytesBetween( pre_string, terminator, buffer, length) class Stream : public Print { - private: + protected: unsigned long _timeout; // number of milliseconds to wait for the next char before aborting timed read unsigned long _startMillis; // used for timeout measurement int timedRead(); // private method to read stream with timeout diff --git a/hardware/arduino/cores/arduino/USBAPI.h b/hardware/arduino/cores/arduino/USBAPI.h index eb2e5937db0..7a14285db05 100644 --- a/hardware/arduino/cores/arduino/USBAPI.h +++ b/hardware/arduino/cores/arduino/USBAPI.h @@ -30,7 +30,8 @@ class Serial_ : public Stream private: ring_buffer *_cdc_rx_buffer; public: - void begin(uint16_t baud_count); + void begin(unsigned long); + void begin(unsigned long, uint8_t); void end(void); virtual int available(void); @@ -193,4 +194,4 @@ void USB_Flush(uint8_t ep); #endif -#endif /* if defined(USBCON) */ \ No newline at end of file +#endif /* if defined(USBCON) */ diff --git a/hardware/arduino/cores/arduino/WInterrupts.c b/hardware/arduino/cores/arduino/WInterrupts.c index de49cd16e3b..d3fbf100e3e 100644 --- a/hardware/arduino/cores/arduino/WInterrupts.c +++ b/hardware/arduino/cores/arduino/WInterrupts.c @@ -51,14 +51,14 @@ void attachInterrupt(uint8_t interruptNum, void (*userFunc)(void), int mode) { // I hate doing this, but the register assignment differs between the 1280/2560 // and the 32U4. Since avrlib defines registers PCMSK1 and PCMSK2 that aren't // even present on the 32U4 this is the only way to distinguish between them. - case 0: - EICRA = (EICRA & ~((1<(lhs); + if (!a.concat(num)) a.invalidate(); + return a; +} + +StringSumHelper & operator + (const StringSumHelper &lhs, double num) +{ + StringSumHelper &a = const_cast(lhs); + if (!a.concat(num)) a.invalidate(); + return a; +} + +StringSumHelper & operator + (const StringSumHelper &lhs, const __FlashStringHelper *rhs) +{ + StringSumHelper &a = const_cast(lhs); + if (!a.concat(rhs)) a.invalidate(); + return a; +} + /*********************************************/ /* Comparison */ /*********************************************/ @@ -527,11 +611,6 @@ int String::lastIndexOf(const String &s2, unsigned int fromIndex) const return found; } -String String::substring( unsigned int left ) const -{ - return substring(left, len); -} - String String::substring(unsigned int left, unsigned int right) const { if (left > right) { @@ -604,6 +683,22 @@ void String::replace(const String& find, const String& replace) } } +void String::remove(unsigned int index){ + if (index >= len) { return; } + int count = len - index; + remove(index, count); +} + +void String::remove(unsigned int index, unsigned int count){ + if (index >= len) { return; } + if (count <= 0) { return; } + if (index + count > len) { count = len - index; } + char *writeTo = buffer + index; + len = len - count; + strncpy(writeTo, buffer + index + count,len - index); + buffer[len] = 0; +} + void String::toLowerCase(void) { if (!buffer) return; @@ -642,4 +737,8 @@ long String::toInt(void) const return 0; } - +float String::toFloat(void) const +{ + if (buffer) return float(atof(buffer)); + return 0; +} diff --git a/hardware/arduino/cores/arduino/WString.h b/hardware/arduino/cores/arduino/WString.h index 947325e5f5d..74024309278 100644 --- a/hardware/arduino/cores/arduino/WString.h +++ b/hardware/arduino/cores/arduino/WString.h @@ -58,6 +58,7 @@ class String // be false). String(const char *cstr = ""); String(const String &str); + String(const __FlashStringHelper *str); #ifdef __GXX_EXPERIMENTAL_CXX0X__ String(String &&rval); String(StringSumHelper &&rval); @@ -68,6 +69,8 @@ class String explicit String(unsigned int, unsigned char base=10); explicit String(long, unsigned char base=10); explicit String(unsigned long, unsigned char base=10); + explicit String(float, unsigned char decimalPlaces=2); + explicit String(double, unsigned char decimalPlaces=2); ~String(void); // memory management @@ -82,6 +85,7 @@ class String // marked as invalid ("if (s)" will be false). String & operator = (const String &rhs); String & operator = (const char *cstr); + String & operator = (const __FlashStringHelper *str); #ifdef __GXX_EXPERIMENTAL_CXX0X__ String & operator = (String &&rval); String & operator = (StringSumHelper &&rval); @@ -100,6 +104,9 @@ class String unsigned char concat(unsigned int num); unsigned char concat(long num); unsigned char concat(unsigned long num); + unsigned char concat(float num); + unsigned char concat(double num); + unsigned char concat(const __FlashStringHelper * str); // if there's not enough memory for the concatenated value, the string // will be left unchanged (but this isn't signalled in any way) @@ -111,6 +118,9 @@ class String String & operator += (unsigned int num) {concat(num); return (*this);} String & operator += (long num) {concat(num); return (*this);} String & operator += (unsigned long num) {concat(num); return (*this);} + String & operator += (float num) {concat(num); return (*this);} + String & operator += (double num) {concat(num); return (*this);} + String & operator += (const __FlashStringHelper *str){concat(str); return (*this);} friend StringSumHelper & operator + (const StringSumHelper &lhs, const String &rhs); friend StringSumHelper & operator + (const StringSumHelper &lhs, const char *cstr); @@ -120,6 +130,9 @@ class String friend StringSumHelper & operator + (const StringSumHelper &lhs, unsigned int num); friend StringSumHelper & operator + (const StringSumHelper &lhs, long num); friend StringSumHelper & operator + (const StringSumHelper &lhs, unsigned long num); + friend StringSumHelper & operator + (const StringSumHelper &lhs, float num); + friend StringSumHelper & operator + (const StringSumHelper &lhs, double num); + friend StringSumHelper & operator + (const StringSumHelper &lhs, const __FlashStringHelper *rhs); // comparison (only works w/ Strings and "strings") operator StringIfHelperType() const { return buffer ? &String::StringIfHelper : 0; } @@ -147,6 +160,7 @@ class String void getBytes(unsigned char *buf, unsigned int bufsize, unsigned int index=0) const; void toCharArray(char *buf, unsigned int bufsize, unsigned int index=0) const {getBytes((unsigned char *)buf, bufsize, index);} + const char * c_str() const { return buffer; } // search int indexOf( char ch ) const; @@ -157,24 +171,26 @@ class String int lastIndexOf( char ch, unsigned int fromIndex ) const; int lastIndexOf( const String &str ) const; int lastIndexOf( const String &str, unsigned int fromIndex ) const; - String substring( unsigned int beginIndex ) const; + String substring( unsigned int beginIndex ) const { return substring(beginIndex, len); }; String substring( unsigned int beginIndex, unsigned int endIndex ) const; // modification void replace(char find, char replace); void replace(const String& find, const String& replace); + void remove(unsigned int index); + void remove(unsigned int index, unsigned int count); void toLowerCase(void); void toUpperCase(void); void trim(void); // parsing/conversion long toInt(void) const; + float toFloat(void) const; protected: char *buffer; // the actual char array unsigned int capacity; // the array length minus one (for the '\0') unsigned int len; // the String length (not counting the '\0') - unsigned char flags; // unused, for future features protected: void init(void); void invalidate(void); @@ -183,6 +199,7 @@ class String // copy and move String & copy(const char *cstr, unsigned int length); + String & copy(const __FlashStringHelper *pstr, unsigned int length); #ifdef __GXX_EXPERIMENTAL_CXX0X__ void move(String &rhs); #endif @@ -199,6 +216,8 @@ class StringSumHelper : public String StringSumHelper(unsigned int num) : String(num) {} StringSumHelper(long num) : String(num) {} StringSumHelper(unsigned long num) : String(num) {} + StringSumHelper(float num) : String(num) {} + StringSumHelper(double num) : String(num) {} }; #endif // __cplusplus diff --git a/hardware/arduino/cores/arduino/binary.h b/hardware/arduino/cores/arduino/binary.h index af1498033ab..aec4c733d4c 100644 --- a/hardware/arduino/cores/arduino/binary.h +++ b/hardware/arduino/cores/arduino/binary.h @@ -1,3 +1,22 @@ +/* + binary.h - Definitions for binary constants + Copyright (c) 2006 David A. Mellis. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + #ifndef Binary_h #define Binary_h diff --git a/hardware/arduino/cores/arduino/main.cpp b/hardware/arduino/cores/arduino/main.cpp index 3d4e079d2a0..0ad6962151c 100644 --- a/hardware/arduino/cores/arduino/main.cpp +++ b/hardware/arduino/cores/arduino/main.cpp @@ -1,3 +1,22 @@ +/* + main.cpp - Main loop for Arduino sketches + Copyright (c) 2005-2013 Arduino Team. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + #include int main(void) diff --git a/hardware/arduino/cores/arduino/wiring_analog.c b/hardware/arduino/cores/arduino/wiring_analog.c index 3f19c7f88e9..8feead9577c 100644 --- a/hardware/arduino/cores/arduino/wiring_analog.c +++ b/hardware/arduino/cores/arduino/wiring_analog.c @@ -41,22 +41,22 @@ int analogRead(uint8_t pin) { uint8_t low, high; -#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) +#if defined(analogPinToChannel) +#if defined(__AVR_ATmega32U4__) + if (pin >= 18) pin -= 18; // allow for channel or pin numbers +#endif + pin = analogPinToChannel(pin); +#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) if (pin >= 54) pin -= 54; // allow for channel or pin numbers #elif defined(__AVR_ATmega32U4__) if (pin >= 18) pin -= 18; // allow for channel or pin numbers -#elif defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega644P__) +#elif defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega644__) || defined(__AVR_ATmega644A__) || defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644PA__) if (pin >= 24) pin -= 24; // allow for channel or pin numbers -#elif defined(analogPinToChannel) && (defined(__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)) - pin = analogPinToChannel(pin); #else if (pin >= 14) pin -= 14; // allow for channel or pin numbers #endif - -#if defined(__AVR_ATmega32U4__) - pin = analogPinToChannel(pin); - ADCSRB = (ADCSRB & ~(1 << MUX5)) | (((pin >> 3) & 0x01) << MUX5); -#elif defined(ADCSRB) && defined(MUX5) + +#if defined(ADCSRB) && defined(MUX5) // the MUX5 bit of ADCSRB selects whether we're reading from channels // 0 to 7 (MUX5 low) or 8 to 15 (MUX5 high). ADCSRB = (ADCSRB & ~(1 << MUX5)) | (((pin >> 3) & 0x01) << MUX5); diff --git a/hardware/arduino/cores/arduino/wiring_private.h b/hardware/arduino/cores/arduino/wiring_private.h index f678265679e..c366005c416 100755 --- a/hardware/arduino/cores/arduino/wiring_private.h +++ b/hardware/arduino/cores/arduino/wiring_private.h @@ -54,10 +54,10 @@ extern "C"{ #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) #define EXTERNAL_NUM_INTERRUPTS 8 -#elif defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega644P__) +#elif defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega644__) || defined(__AVR_ATmega644A__) || defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644PA__) #define EXTERNAL_NUM_INTERRUPTS 3 #elif defined(__AVR_ATmega32U4__) -#define EXTERNAL_NUM_INTERRUPTS 4 +#define EXTERNAL_NUM_INTERRUPTS 5 #else #define EXTERNAL_NUM_INTERRUPTS 2 #endif diff --git a/hardware/arduino/cores/robot/Arduino.h b/hardware/arduino/cores/robot/Arduino.h new file mode 100755 index 00000000000..93a3525d655 --- /dev/null +++ b/hardware/arduino/cores/robot/Arduino.h @@ -0,0 +1,234 @@ +/* + Arduino.h - Main include file for the Arduino SDK + Copyright (c) 2005-2013 Arduino Team. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef Arduino_h +#define Arduino_h + +#include +#include +#include + +#include +#include +#include + +#include "binary.h" + +#ifdef __cplusplus +extern "C"{ +#endif + +#define HIGH 0x1 +#define LOW 0x0 + +#define INPUT 0x0 +#define OUTPUT 0x1 +#define INPUT_PULLUP 0x2 + +#define true 0x1 +#define false 0x0 + +#define PI 3.1415926535897932384626433832795 +#define HALF_PI 1.5707963267948966192313216916398 +#define TWO_PI 6.283185307179586476925286766559 +#define DEG_TO_RAD 0.017453292519943295769236907684886 +#define RAD_TO_DEG 57.295779513082320876798154814105 + +#define SERIAL 0x0 +#define DISPLAY 0x1 + +#define LSBFIRST 0 +#define MSBFIRST 1 + +#define CHANGE 1 +#define FALLING 2 +#define RISING 3 + +#if defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__) || defined(__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) +#define DEFAULT 0 +#define EXTERNAL 1 +#define INTERNAL 2 +#else +#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega644__) || defined(__AVR_ATmega644A__) || defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644PA__) +#define INTERNAL1V1 2 +#define INTERNAL2V56 3 +#else +#define INTERNAL 3 +#endif +#define DEFAULT 1 +#define EXTERNAL 0 +#endif + +// undefine stdlib's abs if encountered +#ifdef abs +#undef abs +#endif + +#define min(a,b) ((a)<(b)?(a):(b)) +#define max(a,b) ((a)>(b)?(a):(b)) +#define abs(x) ((x)>0?(x):-(x)) +#define constrain(amt,low,high) ((amt)<(low)?(low):((amt)>(high)?(high):(amt))) +#define round(x) ((x)>=0?(long)((x)+0.5):(long)((x)-0.5)) +#define radians(deg) ((deg)*DEG_TO_RAD) +#define degrees(rad) ((rad)*RAD_TO_DEG) +#define sq(x) ((x)*(x)) + +#define interrupts() sei() +#define noInterrupts() cli() + +#define clockCyclesPerMicrosecond() ( F_CPU / 1000000L ) +#define clockCyclesToMicroseconds(a) ( (a) / clockCyclesPerMicrosecond() ) +#define microsecondsToClockCycles(a) ( (a) * clockCyclesPerMicrosecond() ) + +#define lowByte(w) ((uint8_t) ((w) & 0xff)) +#define highByte(w) ((uint8_t) ((w) >> 8)) + +#define bitRead(value, bit) (((value) >> (bit)) & 0x01) +#define bitSet(value, bit) ((value) |= (1UL << (bit))) +#define bitClear(value, bit) ((value) &= ~(1UL << (bit))) +#define bitWrite(value, bit, bitvalue) (bitvalue ? bitSet(value, bit) : bitClear(value, bit)) + + +typedef unsigned int word; + +#define bit(b) (1UL << (b)) + +typedef uint8_t boolean; +typedef uint8_t byte; + +void init(void); + +void pinMode(uint8_t, uint8_t); +void digitalWrite(uint8_t, uint8_t); +int digitalRead(uint8_t); +int analogRead(uint8_t); +void analogReference(uint8_t mode); +void analogWrite(uint8_t, int); + +unsigned long millis(void); +unsigned long micros(void); +void delay(unsigned long); +void delayMicroseconds(unsigned int us); +unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout); + +void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val); +uint8_t shiftIn(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder); + +void attachInterrupt(uint8_t, void (*)(void), int mode); +void detachInterrupt(uint8_t); + +void setup(void); +void loop(void); + +// Get the bit location within the hardware port of the given virtual pin. +// This comes from the pins_*.c file for the active board configuration. + +#define analogInPinToBit(P) (P) + +// On the ATmega1280, the addresses of some of the port registers are +// greater than 255, so we can't store them in uint8_t's. +extern const uint16_t PROGMEM port_to_mode_PGM[]; +extern const uint16_t PROGMEM port_to_input_PGM[]; +extern const uint16_t PROGMEM port_to_output_PGM[]; + +extern const uint8_t PROGMEM digital_pin_to_port_PGM[]; +// extern const uint8_t PROGMEM digital_pin_to_bit_PGM[]; +extern const uint8_t PROGMEM digital_pin_to_bit_mask_PGM[]; +extern const uint8_t PROGMEM digital_pin_to_timer_PGM[]; + +// Get the bit location within the hardware port of the given virtual pin. +// This comes from the pins_*.c file for the active board configuration. +// +// These perform slightly better as macros compared to inline functions +// +#define digitalPinToPort(P) ( pgm_read_byte( digital_pin_to_port_PGM + (P) ) ) +#define digitalPinToBitMask(P) ( pgm_read_byte( digital_pin_to_bit_mask_PGM + (P) ) ) +#define digitalPinToTimer(P) ( pgm_read_byte( digital_pin_to_timer_PGM + (P) ) ) +#define analogInPinToBit(P) (P) +#define portOutputRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_output_PGM + (P))) ) +#define portInputRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_input_PGM + (P))) ) +#define portModeRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_mode_PGM + (P))) ) + +#define NOT_A_PIN 0 +#define NOT_A_PORT 0 + +#ifdef ARDUINO_MAIN +#define PA 1 +#define PB 2 +#define PC 3 +#define PD 4 +#define PE 5 +#define PF 6 +#define PG 7 +#define PH 8 +#define PJ 10 +#define PK 11 +#define PL 12 +#endif + +#define NOT_ON_TIMER 0 +#define TIMER0A 1 +#define TIMER0B 2 +#define TIMER1A 3 +#define TIMER1B 4 +#define TIMER2 5 +#define TIMER2A 6 +#define TIMER2B 7 + +#define TIMER3A 8 +#define TIMER3B 9 +#define TIMER3C 10 +#define TIMER4A 11 +#define TIMER4B 12 +#define TIMER4C 13 +#define TIMER4D 14 +#define TIMER5A 15 +#define TIMER5B 16 +#define TIMER5C 17 + +#ifdef __cplusplus +} // extern "C" +#endif + +#ifdef __cplusplus +#include "WCharacter.h" +#include "WString.h" +#include "HardwareSerial.h" + +uint16_t makeWord(uint16_t w); +uint16_t makeWord(byte h, byte l); + +#define word(...) makeWord(__VA_ARGS__) + +unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout = 1000000L); + +void tone(uint8_t _pin, unsigned int frequency, unsigned long duration = 0); +void noTone(uint8_t _pin); + +// WMath prototypes +long random(long); +long random(long, long); +void randomSeed(unsigned int); +long map(long, long, long, long, long); + +#endif + +#include "pins_arduino.h" + +#endif diff --git a/hardware/arduino/cores/robot/CDC.cpp b/hardware/arduino/cores/robot/CDC.cpp new file mode 100644 index 00000000000..701e48398fc --- /dev/null +++ b/hardware/arduino/cores/robot/CDC.cpp @@ -0,0 +1,239 @@ + + +/* Copyright (c) 2011, Peter Barrett +** +** Permission to use, copy, modify, and/or distribute this software for +** any purpose with or without fee is hereby granted, provided that the +** above copyright notice and this permission notice appear in all copies. +** +** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL +** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED +** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR +** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES +** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS +** SOFTWARE. +*/ + +#include "Platform.h" +#include "USBAPI.h" +#include + +#if defined(USBCON) +#ifdef CDC_ENABLED + +#if (RAMEND < 1000) +#define SERIAL_BUFFER_SIZE 16 +#else +#define SERIAL_BUFFER_SIZE 64 +#endif + +struct ring_buffer +{ + unsigned char buffer[SERIAL_BUFFER_SIZE]; + volatile int head; + volatile int tail; +}; + +ring_buffer cdc_rx_buffer = { { 0 }, 0, 0}; + +typedef struct +{ + u32 dwDTERate; + u8 bCharFormat; + u8 bParityType; + u8 bDataBits; + u8 lineState; +} LineInfo; + +static volatile LineInfo _usbLineInfo = { 57600, 0x00, 0x00, 0x00, 0x00 }; + +#define WEAK __attribute__ ((weak)) + +extern const CDCDescriptor _cdcInterface PROGMEM; +const CDCDescriptor _cdcInterface = +{ + D_IAD(0,2,CDC_COMMUNICATION_INTERFACE_CLASS,CDC_ABSTRACT_CONTROL_MODEL,1), + + // CDC communication interface + D_INTERFACE(CDC_ACM_INTERFACE,1,CDC_COMMUNICATION_INTERFACE_CLASS,CDC_ABSTRACT_CONTROL_MODEL,0), + D_CDCCS(CDC_HEADER,0x10,0x01), // Header (1.10 bcd) + D_CDCCS(CDC_CALL_MANAGEMENT,1,1), // Device handles call management (not) + D_CDCCS4(CDC_ABSTRACT_CONTROL_MANAGEMENT,6), // SET_LINE_CODING, GET_LINE_CODING, SET_CONTROL_LINE_STATE supported + D_CDCCS(CDC_UNION,CDC_ACM_INTERFACE,CDC_DATA_INTERFACE), // Communication interface is master, data interface is slave 0 + D_ENDPOINT(USB_ENDPOINT_IN (CDC_ENDPOINT_ACM),USB_ENDPOINT_TYPE_INTERRUPT,0x10,0x40), + + // CDC data interface + D_INTERFACE(CDC_DATA_INTERFACE,2,CDC_DATA_INTERFACE_CLASS,0,0), + D_ENDPOINT(USB_ENDPOINT_OUT(CDC_ENDPOINT_OUT),USB_ENDPOINT_TYPE_BULK,0x40,0), + D_ENDPOINT(USB_ENDPOINT_IN (CDC_ENDPOINT_IN ),USB_ENDPOINT_TYPE_BULK,0x40,0) +}; + +int WEAK CDC_GetInterface(u8* interfaceNum) +{ + interfaceNum[0] += 2; // uses 2 + return USB_SendControl(TRANSFER_PGM,&_cdcInterface,sizeof(_cdcInterface)); +} + +bool WEAK CDC_Setup(Setup& setup) +{ + u8 r = setup.bRequest; + u8 requestType = setup.bmRequestType; + + if (REQUEST_DEVICETOHOST_CLASS_INTERFACE == requestType) + { + if (CDC_GET_LINE_CODING == r) + { + USB_SendControl(0,(void*)&_usbLineInfo,7); + return true; + } + } + + if (REQUEST_HOSTTODEVICE_CLASS_INTERFACE == requestType) + { + if (CDC_SET_LINE_CODING == r) + { + USB_RecvControl((void*)&_usbLineInfo,7); + return true; + } + + if (CDC_SET_CONTROL_LINE_STATE == r) + { + _usbLineInfo.lineState = setup.wValueL; + + // auto-reset into the bootloader is triggered when the port, already + // open at 1200 bps, is closed. this is the signal to start the watchdog + // with a relatively long period so it can finish housekeeping tasks + // like servicing endpoints before the sketch ends + if (1200 == _usbLineInfo.dwDTERate) { + // We check DTR state to determine if host port is open (bit 0 of lineState). + if ((_usbLineInfo.lineState & 0x01) == 0) { + *(uint16_t *)0x0800 = 0x7777; + wdt_enable(WDTO_120MS); + } else { + // Most OSs do some intermediate steps when configuring ports and DTR can + // twiggle more than once before stabilizing. + // To avoid spurious resets we set the watchdog to 250ms and eventually + // cancel if DTR goes back high. + + wdt_disable(); + wdt_reset(); + *(uint16_t *)0x0800 = 0x0; + } + } + return true; + } + } + return false; +} + + +int _serialPeek = -1; +void Serial_::begin(uint16_t baud_count) +{ +} + +void Serial_::end(void) +{ +} + +void Serial_::accept(void) +{ + ring_buffer *buffer = &cdc_rx_buffer; + int i = (unsigned int)(buffer->head+1) % SERIAL_BUFFER_SIZE; + + // if we should be storing the received character into the location + // just before the tail (meaning that the head would advance to the + // current location of the tail), we're about to overflow the buffer + // and so we don't write the character or advance the head. + + // while we have room to store a byte + while (i != buffer->tail) { + int c = USB_Recv(CDC_RX); + if (c == -1) + break; // no more data + buffer->buffer[buffer->head] = c; + buffer->head = i; + + i = (unsigned int)(buffer->head+1) % SERIAL_BUFFER_SIZE; + } +} + +int Serial_::available(void) +{ + ring_buffer *buffer = &cdc_rx_buffer; + return (unsigned int)(SERIAL_BUFFER_SIZE + buffer->head - buffer->tail) % SERIAL_BUFFER_SIZE; +} + +int Serial_::peek(void) +{ + ring_buffer *buffer = &cdc_rx_buffer; + if (buffer->head == buffer->tail) { + return -1; + } else { + return buffer->buffer[buffer->tail]; + } +} + +int Serial_::read(void) +{ + ring_buffer *buffer = &cdc_rx_buffer; + // if the head isn't ahead of the tail, we don't have any characters + if (buffer->head == buffer->tail) { + return -1; + } else { + unsigned char c = buffer->buffer[buffer->tail]; + buffer->tail = (unsigned int)(buffer->tail + 1) % SERIAL_BUFFER_SIZE; + return c; + } +} + +void Serial_::flush(void) +{ + USB_Flush(CDC_TX); +} + +size_t Serial_::write(uint8_t c) +{ + /* only try to send bytes if the high-level CDC connection itself + is open (not just the pipe) - the OS should set lineState when the port + is opened and clear lineState when the port is closed. + bytes sent before the user opens the connection or after + the connection is closed are lost - just like with a UART. */ + + // TODO - ZE - check behavior on different OSes and test what happens if an + // open connection isn't broken cleanly (cable is yanked out, host dies + // or locks up, or host virtual serial port hangs) + if (_usbLineInfo.lineState > 0) { + int r = USB_Send(CDC_TX,&c,1); + if (r > 0) { + return r; + } else { + setWriteError(); + return 0; + } + } + setWriteError(); + return 0; +} + +// This operator is a convenient way for a sketch to check whether the +// port has actually been configured and opened by the host (as opposed +// to just being connected to the host). It can be used, for example, in +// setup() before printing to ensure that an application on the host is +// actually ready to receive and display the data. +// We add a short delay before returning to fix a bug observed by Federico +// where the port is configured (lineState != 0) but not quite opened. +Serial_::operator bool() { + bool result = false; + if (_usbLineInfo.lineState > 0) + result = true; + delay(10); + return result; +} + +Serial_ Serial; + +#endif +#endif /* if defined(USBCON) */ diff --git a/hardware/arduino/cores/robot/Client.h b/hardware/arduino/cores/robot/Client.h new file mode 100644 index 00000000000..b8e5d935f2a --- /dev/null +++ b/hardware/arduino/cores/robot/Client.h @@ -0,0 +1,45 @@ +/* + Client.h - Base class that provides Client + Copyright (c) 2011 Adrian McEwen. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef client_h +#define client_h +#include "Print.h" +#include "Stream.h" +#include "IPAddress.h" + +class Client : public Stream { + +public: + virtual int connect(IPAddress ip, uint16_t port) =0; + virtual int connect(const char *host, uint16_t port) =0; + virtual size_t write(uint8_t) =0; + virtual size_t write(const uint8_t *buf, size_t size) =0; + virtual int available() = 0; + virtual int read() = 0; + virtual int read(uint8_t *buf, size_t size) = 0; + virtual int peek() = 0; + virtual void flush() = 0; + virtual void stop() = 0; + virtual uint8_t connected() = 0; + virtual operator bool() = 0; +protected: + uint8_t* rawIPAddress(IPAddress& addr) { return addr.raw_address(); }; +}; + +#endif diff --git a/hardware/arduino/cores/robot/HID.cpp b/hardware/arduino/cores/robot/HID.cpp new file mode 100644 index 00000000000..ac636084493 --- /dev/null +++ b/hardware/arduino/cores/robot/HID.cpp @@ -0,0 +1,520 @@ + + +/* Copyright (c) 2011, Peter Barrett +** +** Permission to use, copy, modify, and/or distribute this software for +** any purpose with or without fee is hereby granted, provided that the +** above copyright notice and this permission notice appear in all copies. +** +** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL +** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED +** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR +** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES +** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS +** SOFTWARE. +*/ + +#include "Platform.h" +#include "USBAPI.h" +#include "USBDesc.h" + +#if defined(USBCON) +#ifdef HID_ENABLED + +//#define RAWHID_ENABLED + +// Singletons for mouse and keyboard + +Mouse_ Mouse; +Keyboard_ Keyboard; + +//================================================================================ +//================================================================================ + +// HID report descriptor + +#define LSB(_x) ((_x) & 0xFF) +#define MSB(_x) ((_x) >> 8) + +#define RAWHID_USAGE_PAGE 0xFFC0 +#define RAWHID_USAGE 0x0C00 +#define RAWHID_TX_SIZE 64 +#define RAWHID_RX_SIZE 64 + +extern const u8 _hidReportDescriptor[] PROGMEM; +const u8 _hidReportDescriptor[] = { + + // Mouse + 0x05, 0x01, // USAGE_PAGE (Generic Desktop) // 54 + 0x09, 0x02, // USAGE (Mouse) + 0xa1, 0x01, // COLLECTION (Application) + 0x09, 0x01, // USAGE (Pointer) + 0xa1, 0x00, // COLLECTION (Physical) + 0x85, 0x01, // REPORT_ID (1) + 0x05, 0x09, // USAGE_PAGE (Button) + 0x19, 0x01, // USAGE_MINIMUM (Button 1) + 0x29, 0x03, // USAGE_MAXIMUM (Button 3) + 0x15, 0x00, // LOGICAL_MINIMUM (0) + 0x25, 0x01, // LOGICAL_MAXIMUM (1) + 0x95, 0x03, // REPORT_COUNT (3) + 0x75, 0x01, // REPORT_SIZE (1) + 0x81, 0x02, // INPUT (Data,Var,Abs) + 0x95, 0x01, // REPORT_COUNT (1) + 0x75, 0x05, // REPORT_SIZE (5) + 0x81, 0x03, // INPUT (Cnst,Var,Abs) + 0x05, 0x01, // USAGE_PAGE (Generic Desktop) + 0x09, 0x30, // USAGE (X) + 0x09, 0x31, // USAGE (Y) + 0x09, 0x38, // USAGE (Wheel) + 0x15, 0x81, // LOGICAL_MINIMUM (-127) + 0x25, 0x7f, // LOGICAL_MAXIMUM (127) + 0x75, 0x08, // REPORT_SIZE (8) + 0x95, 0x03, // REPORT_COUNT (3) + 0x81, 0x06, // INPUT (Data,Var,Rel) + 0xc0, // END_COLLECTION + 0xc0, // END_COLLECTION + + // Keyboard + 0x05, 0x01, // USAGE_PAGE (Generic Desktop) // 47 + 0x09, 0x06, // USAGE (Keyboard) + 0xa1, 0x01, // COLLECTION (Application) + 0x85, 0x02, // REPORT_ID (2) + 0x05, 0x07, // USAGE_PAGE (Keyboard) + + 0x19, 0xe0, // USAGE_MINIMUM (Keyboard LeftControl) + 0x29, 0xe7, // USAGE_MAXIMUM (Keyboard Right GUI) + 0x15, 0x00, // LOGICAL_MINIMUM (0) + 0x25, 0x01, // LOGICAL_MAXIMUM (1) + 0x75, 0x01, // REPORT_SIZE (1) + + 0x95, 0x08, // REPORT_COUNT (8) + 0x81, 0x02, // INPUT (Data,Var,Abs) + 0x95, 0x01, // REPORT_COUNT (1) + 0x75, 0x08, // REPORT_SIZE (8) + 0x81, 0x03, // INPUT (Cnst,Var,Abs) + + 0x95, 0x06, // REPORT_COUNT (6) + 0x75, 0x08, // REPORT_SIZE (8) + 0x15, 0x00, // LOGICAL_MINIMUM (0) + 0x25, 0x65, // LOGICAL_MAXIMUM (101) + 0x05, 0x07, // USAGE_PAGE (Keyboard) + + 0x19, 0x00, // USAGE_MINIMUM (Reserved (no event indicated)) + 0x29, 0x65, // USAGE_MAXIMUM (Keyboard Application) + 0x81, 0x00, // INPUT (Data,Ary,Abs) + 0xc0, // END_COLLECTION + +#if RAWHID_ENABLED + // RAW HID + 0x06, LSB(RAWHID_USAGE_PAGE), MSB(RAWHID_USAGE_PAGE), // 30 + 0x0A, LSB(RAWHID_USAGE), MSB(RAWHID_USAGE), + + 0xA1, 0x01, // Collection 0x01 + 0x85, 0x03, // REPORT_ID (3) + 0x75, 0x08, // report size = 8 bits + 0x15, 0x00, // logical minimum = 0 + 0x26, 0xFF, 0x00, // logical maximum = 255 + + 0x95, 64, // report count TX + 0x09, 0x01, // usage + 0x81, 0x02, // Input (array) + + 0x95, 64, // report count RX + 0x09, 0x02, // usage + 0x91, 0x02, // Output (array) + 0xC0 // end collection +#endif +}; + +extern const HIDDescriptor _hidInterface PROGMEM; +const HIDDescriptor _hidInterface = +{ + D_INTERFACE(HID_INTERFACE,1,3,0,0), + D_HIDREPORT(sizeof(_hidReportDescriptor)), + D_ENDPOINT(USB_ENDPOINT_IN (HID_ENDPOINT_INT),USB_ENDPOINT_TYPE_INTERRUPT,0x40,0x01) +}; + +//================================================================================ +//================================================================================ +// Driver + +u8 _hid_protocol = 1; +u8 _hid_idle = 1; + +#define WEAK __attribute__ ((weak)) + +int WEAK HID_GetInterface(u8* interfaceNum) +{ + interfaceNum[0] += 1; // uses 1 + return USB_SendControl(TRANSFER_PGM,&_hidInterface,sizeof(_hidInterface)); +} + +int WEAK HID_GetDescriptor(int i) +{ + return USB_SendControl(TRANSFER_PGM,_hidReportDescriptor,sizeof(_hidReportDescriptor)); +} + +void WEAK HID_SendReport(u8 id, const void* data, int len) +{ + USB_Send(HID_TX, &id, 1); + USB_Send(HID_TX | TRANSFER_RELEASE,data,len); +} + +bool WEAK HID_Setup(Setup& setup) +{ + u8 r = setup.bRequest; + u8 requestType = setup.bmRequestType; + if (REQUEST_DEVICETOHOST_CLASS_INTERFACE == requestType) + { + if (HID_GET_REPORT == r) + { + //HID_GetReport(); + return true; + } + if (HID_GET_PROTOCOL == r) + { + //Send8(_hid_protocol); // TODO + return true; + } + } + + if (REQUEST_HOSTTODEVICE_CLASS_INTERFACE == requestType) + { + if (HID_SET_PROTOCOL == r) + { + _hid_protocol = setup.wValueL; + return true; + } + + if (HID_SET_IDLE == r) + { + _hid_idle = setup.wValueL; + return true; + } + } + return false; +} + +//================================================================================ +//================================================================================ +// Mouse + +Mouse_::Mouse_(void) : _buttons(0) +{ +} + +void Mouse_::begin(void) +{ +} + +void Mouse_::end(void) +{ +} + +void Mouse_::click(uint8_t b) +{ + _buttons = b; + move(0,0,0); + _buttons = 0; + move(0,0,0); +} + +void Mouse_::move(signed char x, signed char y, signed char wheel) +{ + u8 m[4]; + m[0] = _buttons; + m[1] = x; + m[2] = y; + m[3] = wheel; + HID_SendReport(1,m,4); +} + +void Mouse_::buttons(uint8_t b) +{ + if (b != _buttons) + { + _buttons = b; + move(0,0,0); + } +} + +void Mouse_::press(uint8_t b) +{ + buttons(_buttons | b); +} + +void Mouse_::release(uint8_t b) +{ + buttons(_buttons & ~b); +} + +bool Mouse_::isPressed(uint8_t b) +{ + if ((b & _buttons) > 0) + return true; + return false; +} + +//================================================================================ +//================================================================================ +// Keyboard + +Keyboard_::Keyboard_(void) +{ +} + +void Keyboard_::begin(void) +{ +} + +void Keyboard_::end(void) +{ +} + +void Keyboard_::sendReport(KeyReport* keys) +{ + HID_SendReport(2,keys,sizeof(KeyReport)); +} + +extern +const uint8_t _asciimap[128] PROGMEM; + +#define SHIFT 0x80 +const uint8_t _asciimap[128] = +{ + 0x00, // NUL + 0x00, // SOH + 0x00, // STX + 0x00, // ETX + 0x00, // EOT + 0x00, // ENQ + 0x00, // ACK + 0x00, // BEL + 0x2a, // BS Backspace + 0x2b, // TAB Tab + 0x28, // LF Enter + 0x00, // VT + 0x00, // FF + 0x00, // CR + 0x00, // SO + 0x00, // SI + 0x00, // DEL + 0x00, // DC1 + 0x00, // DC2 + 0x00, // DC3 + 0x00, // DC4 + 0x00, // NAK + 0x00, // SYN + 0x00, // ETB + 0x00, // CAN + 0x00, // EM + 0x00, // SUB + 0x00, // ESC + 0x00, // FS + 0x00, // GS + 0x00, // RS + 0x00, // US + + 0x2c, // ' ' + 0x1e|SHIFT, // ! + 0x34|SHIFT, // " + 0x20|SHIFT, // # + 0x21|SHIFT, // $ + 0x22|SHIFT, // % + 0x24|SHIFT, // & + 0x34, // ' + 0x26|SHIFT, // ( + 0x27|SHIFT, // ) + 0x25|SHIFT, // * + 0x2e|SHIFT, // + + 0x36, // , + 0x2d, // - + 0x37, // . + 0x38, // / + 0x27, // 0 + 0x1e, // 1 + 0x1f, // 2 + 0x20, // 3 + 0x21, // 4 + 0x22, // 5 + 0x23, // 6 + 0x24, // 7 + 0x25, // 8 + 0x26, // 9 + 0x33|SHIFT, // : + 0x33, // ; + 0x36|SHIFT, // < + 0x2e, // = + 0x37|SHIFT, // > + 0x38|SHIFT, // ? + 0x1f|SHIFT, // @ + 0x04|SHIFT, // A + 0x05|SHIFT, // B + 0x06|SHIFT, // C + 0x07|SHIFT, // D + 0x08|SHIFT, // E + 0x09|SHIFT, // F + 0x0a|SHIFT, // G + 0x0b|SHIFT, // H + 0x0c|SHIFT, // I + 0x0d|SHIFT, // J + 0x0e|SHIFT, // K + 0x0f|SHIFT, // L + 0x10|SHIFT, // M + 0x11|SHIFT, // N + 0x12|SHIFT, // O + 0x13|SHIFT, // P + 0x14|SHIFT, // Q + 0x15|SHIFT, // R + 0x16|SHIFT, // S + 0x17|SHIFT, // T + 0x18|SHIFT, // U + 0x19|SHIFT, // V + 0x1a|SHIFT, // W + 0x1b|SHIFT, // X + 0x1c|SHIFT, // Y + 0x1d|SHIFT, // Z + 0x2f, // [ + 0x31, // bslash + 0x30, // ] + 0x23|SHIFT, // ^ + 0x2d|SHIFT, // _ + 0x35, // ` + 0x04, // a + 0x05, // b + 0x06, // c + 0x07, // d + 0x08, // e + 0x09, // f + 0x0a, // g + 0x0b, // h + 0x0c, // i + 0x0d, // j + 0x0e, // k + 0x0f, // l + 0x10, // m + 0x11, // n + 0x12, // o + 0x13, // p + 0x14, // q + 0x15, // r + 0x16, // s + 0x17, // t + 0x18, // u + 0x19, // v + 0x1a, // w + 0x1b, // x + 0x1c, // y + 0x1d, // z + 0x2f|SHIFT, // + 0x31|SHIFT, // | + 0x30|SHIFT, // } + 0x35|SHIFT, // ~ + 0 // DEL +}; + +uint8_t USBPutChar(uint8_t c); + +// press() adds the specified key (printing, non-printing, or modifier) +// to the persistent key report and sends the report. Because of the way +// USB HID works, the host acts like the key remains pressed until we +// call release(), releaseAll(), or otherwise clear the report and resend. +size_t Keyboard_::press(uint8_t k) +{ + uint8_t i; + if (k >= 136) { // it's a non-printing key (not a modifier) + k = k - 136; + } else if (k >= 128) { // it's a modifier key + _keyReport.modifiers |= (1<<(k-128)); + k = 0; + } else { // it's a printing key + k = pgm_read_byte(_asciimap + k); + if (!k) { + setWriteError(); + return 0; + } + if (k & 0x80) { // it's a capital letter or other character reached with shift + _keyReport.modifiers |= 0x02; // the left shift modifier + k &= 0x7F; + } + } + + // Add k to the key report only if it's not already present + // and if there is an empty slot. + if (_keyReport.keys[0] != k && _keyReport.keys[1] != k && + _keyReport.keys[2] != k && _keyReport.keys[3] != k && + _keyReport.keys[4] != k && _keyReport.keys[5] != k) { + + for (i=0; i<6; i++) { + if (_keyReport.keys[i] == 0x00) { + _keyReport.keys[i] = k; + break; + } + } + if (i == 6) { + setWriteError(); + return 0; + } + } + sendReport(&_keyReport); + return 1; +} + +// release() takes the specified key out of the persistent key report and +// sends the report. This tells the OS the key is no longer pressed and that +// it shouldn't be repeated any more. +size_t Keyboard_::release(uint8_t k) +{ + uint8_t i; + if (k >= 136) { // it's a non-printing key (not a modifier) + k = k - 136; + } else if (k >= 128) { // it's a modifier key + _keyReport.modifiers &= ~(1<<(k-128)); + k = 0; + } else { // it's a printing key + k = pgm_read_byte(_asciimap + k); + if (!k) { + return 0; + } + if (k & 0x80) { // it's a capital letter or other character reached with shift + _keyReport.modifiers &= ~(0x02); // the left shift modifier + k &= 0x7F; + } + } + + // Test the key report to see if k is present. Clear it if it exists. + // Check all positions in case the key is present more than once (which it shouldn't be) + for (i=0; i<6; i++) { + if (0 != k && _keyReport.keys[i] == k) { + _keyReport.keys[i] = 0x00; + } + } + + sendReport(&_keyReport); + return 1; +} + +void Keyboard_::releaseAll(void) +{ + _keyReport.keys[0] = 0; + _keyReport.keys[1] = 0; + _keyReport.keys[2] = 0; + _keyReport.keys[3] = 0; + _keyReport.keys[4] = 0; + _keyReport.keys[5] = 0; + _keyReport.modifiers = 0; + sendReport(&_keyReport); +} + +size_t Keyboard_::write(uint8_t c) +{ + uint8_t p = press(c); // Keydown + uint8_t r = release(c); // Keyup + return (p); // just return the result of press() since release() almost always returns 1 +} + +#endif + +#endif /* if defined(USBCON) */ \ No newline at end of file diff --git a/hardware/arduino/cores/robot/HardwareSerial.cpp b/hardware/arduino/cores/robot/HardwareSerial.cpp new file mode 100644 index 00000000000..eb2365f3337 --- /dev/null +++ b/hardware/arduino/cores/robot/HardwareSerial.cpp @@ -0,0 +1,508 @@ +/* + HardwareSerial.cpp - Hardware serial library for Wiring + Copyright (c) 2006 Nicholas Zambetti. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Modified 23 November 2006 by David A. Mellis + Modified 28 September 2010 by Mark Sproul + Modified 14 August 2012 by Alarus +*/ + +#include +#include +#include +#include +#include "Arduino.h" +#include "wiring_private.h" + +// this next line disables the entire HardwareSerial.cpp, +// this is so I can support Attiny series and any other chip without a uart +#if defined(UBRRH) || defined(UBRR0H) || defined(UBRR1H) || defined(UBRR2H) || defined(UBRR3H) + +#include "HardwareSerial.h" + +/* + * on ATmega8, the uart and its bits are not numbered, so there is no "TXC0" + * definition. + */ +#if !defined(TXC0) +#if defined(TXC) +#define TXC0 TXC +#elif defined(TXC1) +// Some devices have uart1 but no uart0 +#define TXC0 TXC1 +#else +#error TXC0 not definable in HardwareSerial.h +#endif +#endif + +// Define constants and variables for buffering incoming serial data. We're +// using a ring buffer (I think), in which head is the index of the location +// to which to write the next incoming character and tail is the index of the +// location from which to read. +#if (RAMEND < 1000) + #define SERIAL_BUFFER_SIZE 16 +#else + #define SERIAL_BUFFER_SIZE 64 +#endif + +struct ring_buffer +{ + unsigned char buffer[SERIAL_BUFFER_SIZE]; + volatile unsigned int head; + volatile unsigned int tail; +}; + +#if defined(USBCON) + ring_buffer rx_buffer = { { 0 }, 0, 0}; + ring_buffer tx_buffer = { { 0 }, 0, 0}; +#endif +#if defined(UBRRH) || defined(UBRR0H) + ring_buffer rx_buffer = { { 0 }, 0, 0 }; + ring_buffer tx_buffer = { { 0 }, 0, 0 }; +#endif +#if defined(UBRR1H) + ring_buffer rx_buffer1 = { { 0 }, 0, 0 }; + ring_buffer tx_buffer1 = { { 0 }, 0, 0 }; +#endif +#if defined(UBRR2H) + ring_buffer rx_buffer2 = { { 0 }, 0, 0 }; + ring_buffer tx_buffer2 = { { 0 }, 0, 0 }; +#endif +#if defined(UBRR3H) + ring_buffer rx_buffer3 = { { 0 }, 0, 0 }; + ring_buffer tx_buffer3 = { { 0 }, 0, 0 }; +#endif + +inline void store_char(unsigned char c, ring_buffer *buffer) +{ + int i = (unsigned int)(buffer->head + 1) % SERIAL_BUFFER_SIZE; + + // if we should be storing the received character into the location + // just before the tail (meaning that the head would advance to the + // current location of the tail), we're about to overflow the buffer + // and so we don't write the character or advance the head. + if (i != buffer->tail) { + buffer->buffer[buffer->head] = c; + buffer->head = i; + } +} + +#if !defined(USART0_RX_vect) && defined(USART1_RX_vect) +// do nothing - on the 32u4 the first USART is USART1 +#else +#if !defined(USART_RX_vect) && !defined(USART0_RX_vect) && \ + !defined(USART_RXC_vect) + #error "Don't know what the Data Received vector is called for the first UART" +#else + void serialEvent() __attribute__((weak)); + void serialEvent() {} + #define serialEvent_implemented +#if defined(USART_RX_vect) + ISR(USART_RX_vect) +#elif defined(USART0_RX_vect) + ISR(USART0_RX_vect) +#elif defined(USART_RXC_vect) + ISR(USART_RXC_vect) // ATmega8 +#endif + { + #if defined(UDR0) + if (bit_is_clear(UCSR0A, UPE0)) { + unsigned char c = UDR0; + store_char(c, &rx_buffer); + } else { + unsigned char c = UDR0; + }; + #elif defined(UDR) + if (bit_is_clear(UCSRA, PE)) { + unsigned char c = UDR; + store_char(c, &rx_buffer); + } else { + unsigned char c = UDR; + }; + #else + #error UDR not defined + #endif + } +#endif +#endif + +#if defined(USART1_RX_vect) + void serialEvent1() __attribute__((weak)); + void serialEvent1() {} + #define serialEvent1_implemented + ISR(USART1_RX_vect) + { + if (bit_is_clear(UCSR1A, UPE1)) { + unsigned char c = UDR1; + store_char(c, &rx_buffer1); + } else { + unsigned char c = UDR1; + }; + } +#endif + +#if defined(USART2_RX_vect) && defined(UDR2) + void serialEvent2() __attribute__((weak)); + void serialEvent2() {} + #define serialEvent2_implemented + ISR(USART2_RX_vect) + { + if (bit_is_clear(UCSR2A, UPE2)) { + unsigned char c = UDR2; + store_char(c, &rx_buffer2); + } else { + unsigned char c = UDR2; + }; + } +#endif + +#if defined(USART3_RX_vect) && defined(UDR3) + void serialEvent3() __attribute__((weak)); + void serialEvent3() {} + #define serialEvent3_implemented + ISR(USART3_RX_vect) + { + if (bit_is_clear(UCSR3A, UPE3)) { + unsigned char c = UDR3; + store_char(c, &rx_buffer3); + } else { + unsigned char c = UDR3; + }; + } +#endif + +void serialEventRun(void) +{ +#ifdef serialEvent_implemented + if (Serial.available()) serialEvent(); +#endif +#ifdef serialEvent1_implemented + if (Serial1.available()) serialEvent1(); +#endif +#ifdef serialEvent2_implemented + if (Serial2.available()) serialEvent2(); +#endif +#ifdef serialEvent3_implemented + if (Serial3.available()) serialEvent3(); +#endif +} + + +#if !defined(USART0_UDRE_vect) && defined(USART1_UDRE_vect) +// do nothing - on the 32u4 the first USART is USART1 +#else +#if !defined(UART0_UDRE_vect) && !defined(UART_UDRE_vect) && !defined(USART0_UDRE_vect) && !defined(USART_UDRE_vect) + #error "Don't know what the Data Register Empty vector is called for the first UART" +#else +#if defined(UART0_UDRE_vect) +ISR(UART0_UDRE_vect) +#elif defined(UART_UDRE_vect) +ISR(UART_UDRE_vect) +#elif defined(USART0_UDRE_vect) +ISR(USART0_UDRE_vect) +#elif defined(USART_UDRE_vect) +ISR(USART_UDRE_vect) +#endif +{ + if (tx_buffer.head == tx_buffer.tail) { + // Buffer empty, so disable interrupts +#if defined(UCSR0B) + cbi(UCSR0B, UDRIE0); +#else + cbi(UCSRB, UDRIE); +#endif + } + else { + // There is more data in the output buffer. Send the next byte + unsigned char c = tx_buffer.buffer[tx_buffer.tail]; + tx_buffer.tail = (tx_buffer.tail + 1) % SERIAL_BUFFER_SIZE; + + #if defined(UDR0) + UDR0 = c; + #elif defined(UDR) + UDR = c; + #else + #error UDR not defined + #endif + } +} +#endif +#endif + +#ifdef USART1_UDRE_vect +ISR(USART1_UDRE_vect) +{ + if (tx_buffer1.head == tx_buffer1.tail) { + // Buffer empty, so disable interrupts + cbi(UCSR1B, UDRIE1); + } + else { + // There is more data in the output buffer. Send the next byte + unsigned char c = tx_buffer1.buffer[tx_buffer1.tail]; + tx_buffer1.tail = (tx_buffer1.tail + 1) % SERIAL_BUFFER_SIZE; + + UDR1 = c; + } +} +#endif + +#ifdef USART2_UDRE_vect +ISR(USART2_UDRE_vect) +{ + if (tx_buffer2.head == tx_buffer2.tail) { + // Buffer empty, so disable interrupts + cbi(UCSR2B, UDRIE2); + } + else { + // There is more data in the output buffer. Send the next byte + unsigned char c = tx_buffer2.buffer[tx_buffer2.tail]; + tx_buffer2.tail = (tx_buffer2.tail + 1) % SERIAL_BUFFER_SIZE; + + UDR2 = c; + } +} +#endif + +#ifdef USART3_UDRE_vect +ISR(USART3_UDRE_vect) +{ + if (tx_buffer3.head == tx_buffer3.tail) { + // Buffer empty, so disable interrupts + cbi(UCSR3B, UDRIE3); + } + else { + // There is more data in the output buffer. Send the next byte + unsigned char c = tx_buffer3.buffer[tx_buffer3.tail]; + tx_buffer3.tail = (tx_buffer3.tail + 1) % SERIAL_BUFFER_SIZE; + + UDR3 = c; + } +} +#endif + + +// Constructors //////////////////////////////////////////////////////////////// + +HardwareSerial::HardwareSerial(ring_buffer *rx_buffer, ring_buffer *tx_buffer, + volatile uint8_t *ubrrh, volatile uint8_t *ubrrl, + volatile uint8_t *ucsra, volatile uint8_t *ucsrb, + volatile uint8_t *ucsrc, volatile uint8_t *udr, + uint8_t rxen, uint8_t txen, uint8_t rxcie, uint8_t udrie, uint8_t u2x) +{ + _rx_buffer = rx_buffer; + _tx_buffer = tx_buffer; + _ubrrh = ubrrh; + _ubrrl = ubrrl; + _ucsra = ucsra; + _ucsrb = ucsrb; + _ucsrc = ucsrc; + _udr = udr; + _rxen = rxen; + _txen = txen; + _rxcie = rxcie; + _udrie = udrie; + _u2x = u2x; +} + +// Public Methods ////////////////////////////////////////////////////////////// + +void HardwareSerial::begin(unsigned long baud) +{ + uint16_t baud_setting; + bool use_u2x = true; + +#if F_CPU == 16000000UL + // hardcoded exception for compatibility with the bootloader shipped + // with the Duemilanove and previous boards and the firmware on the 8U2 + // on the Uno and Mega 2560. + if (baud == 57600) { + use_u2x = false; + } +#endif + +try_again: + + if (use_u2x) { + *_ucsra = 1 << _u2x; + baud_setting = (F_CPU / 4 / baud - 1) / 2; + } else { + *_ucsra = 0; + baud_setting = (F_CPU / 8 / baud - 1) / 2; + } + + if ((baud_setting > 4095) && use_u2x) + { + use_u2x = false; + goto try_again; + } + + // assign the baud_setting, a.k.a. ubbr (USART Baud Rate Register) + *_ubrrh = baud_setting >> 8; + *_ubrrl = baud_setting; + + transmitting = false; + + sbi(*_ucsrb, _rxen); + sbi(*_ucsrb, _txen); + sbi(*_ucsrb, _rxcie); + cbi(*_ucsrb, _udrie); +} + +void HardwareSerial::begin(unsigned long baud, byte config) +{ + uint16_t baud_setting; + uint8_t current_config; + bool use_u2x = true; + +#if F_CPU == 16000000UL + // hardcoded exception for compatibility with the bootloader shipped + // with the Duemilanove and previous boards and the firmware on the 8U2 + // on the Uno and Mega 2560. + if (baud == 57600) { + use_u2x = false; + } +#endif + +try_again: + + if (use_u2x) { + *_ucsra = 1 << _u2x; + baud_setting = (F_CPU / 4 / baud - 1) / 2; + } else { + *_ucsra = 0; + baud_setting = (F_CPU / 8 / baud - 1) / 2; + } + + if ((baud_setting > 4095) && use_u2x) + { + use_u2x = false; + goto try_again; + } + + // assign the baud_setting, a.k.a. ubbr (USART Baud Rate Register) + *_ubrrh = baud_setting >> 8; + *_ubrrl = baud_setting; + + //set the data bits, parity, and stop bits +#if defined(__AVR_ATmega8__) + config |= 0x80; // select UCSRC register (shared with UBRRH) +#endif + *_ucsrc = config; + + sbi(*_ucsrb, _rxen); + sbi(*_ucsrb, _txen); + sbi(*_ucsrb, _rxcie); + cbi(*_ucsrb, _udrie); +} + +void HardwareSerial::end() +{ + // wait for transmission of outgoing data + while (_tx_buffer->head != _tx_buffer->tail) + ; + + cbi(*_ucsrb, _rxen); + cbi(*_ucsrb, _txen); + cbi(*_ucsrb, _rxcie); + cbi(*_ucsrb, _udrie); + + // clear any received data + _rx_buffer->head = _rx_buffer->tail; +} + +int HardwareSerial::available(void) +{ + return (unsigned int)(SERIAL_BUFFER_SIZE + _rx_buffer->head - _rx_buffer->tail) % SERIAL_BUFFER_SIZE; +} + +int HardwareSerial::peek(void) +{ + if (_rx_buffer->head == _rx_buffer->tail) { + return -1; + } else { + return _rx_buffer->buffer[_rx_buffer->tail]; + } +} + +int HardwareSerial::read(void) +{ + // if the head isn't ahead of the tail, we don't have any characters + if (_rx_buffer->head == _rx_buffer->tail) { + return -1; + } else { + unsigned char c = _rx_buffer->buffer[_rx_buffer->tail]; + _rx_buffer->tail = (unsigned int)(_rx_buffer->tail + 1) % SERIAL_BUFFER_SIZE; + return c; + } +} + +void HardwareSerial::flush() +{ + // UDR is kept full while the buffer is not empty, so TXC triggers when EMPTY && SENT + while (transmitting && ! (*_ucsra & _BV(TXC0))); + transmitting = false; +} + +size_t HardwareSerial::write(uint8_t c) +{ + int i = (_tx_buffer->head + 1) % SERIAL_BUFFER_SIZE; + + // If the output buffer is full, there's nothing for it other than to + // wait for the interrupt handler to empty it a bit + // ???: return 0 here instead? + while (i == _tx_buffer->tail) + ; + + _tx_buffer->buffer[_tx_buffer->head] = c; + _tx_buffer->head = i; + + sbi(*_ucsrb, _udrie); + // clear the TXC bit -- "can be cleared by writing a one to its bit location" + transmitting = true; + sbi(*_ucsra, TXC0); + + return 1; +} + +HardwareSerial::operator bool() { + return true; +} + +// Preinstantiate Objects ////////////////////////////////////////////////////// + +#if defined(UBRRH) && defined(UBRRL) + HardwareSerial Serial(&rx_buffer, &tx_buffer, &UBRRH, &UBRRL, &UCSRA, &UCSRB, &UCSRC, &UDR, RXEN, TXEN, RXCIE, UDRIE, U2X); +#elif defined(UBRR0H) && defined(UBRR0L) + HardwareSerial Serial(&rx_buffer, &tx_buffer, &UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0, RXEN0, TXEN0, RXCIE0, UDRIE0, U2X0); +#elif defined(USBCON) + // do nothing - Serial object and buffers are initialized in CDC code +#else + #error no serial port defined (port 0) +#endif + +#if defined(UBRR1H) + HardwareSerial Serial1(&rx_buffer1, &tx_buffer1, &UBRR1H, &UBRR1L, &UCSR1A, &UCSR1B, &UCSR1C, &UDR1, RXEN1, TXEN1, RXCIE1, UDRIE1, U2X1); +#endif +#if defined(UBRR2H) + HardwareSerial Serial2(&rx_buffer2, &tx_buffer2, &UBRR2H, &UBRR2L, &UCSR2A, &UCSR2B, &UCSR2C, &UDR2, RXEN2, TXEN2, RXCIE2, UDRIE2, U2X2); +#endif +#if defined(UBRR3H) + HardwareSerial Serial3(&rx_buffer3, &tx_buffer3, &UBRR3H, &UBRR3L, &UCSR3A, &UCSR3B, &UCSR3C, &UDR3, RXEN3, TXEN3, RXCIE3, UDRIE3, U2X3); +#endif + +#endif // whole file + diff --git a/hardware/arduino/cores/robot/HardwareSerial.h b/hardware/arduino/cores/robot/HardwareSerial.h new file mode 100644 index 00000000000..a73117f5681 --- /dev/null +++ b/hardware/arduino/cores/robot/HardwareSerial.h @@ -0,0 +1,115 @@ +/* + HardwareSerial.h - Hardware serial library for Wiring + Copyright (c) 2006 Nicholas Zambetti. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Modified 28 September 2010 by Mark Sproul + Modified 14 August 2012 by Alarus +*/ + +#ifndef HardwareSerial_h +#define HardwareSerial_h + +#include + +#include "Stream.h" + +struct ring_buffer; + +class HardwareSerial : public Stream +{ + private: + ring_buffer *_rx_buffer; + ring_buffer *_tx_buffer; + volatile uint8_t *_ubrrh; + volatile uint8_t *_ubrrl; + volatile uint8_t *_ucsra; + volatile uint8_t *_ucsrb; + volatile uint8_t *_ucsrc; + volatile uint8_t *_udr; + uint8_t _rxen; + uint8_t _txen; + uint8_t _rxcie; + uint8_t _udrie; + uint8_t _u2x; + bool transmitting; + public: + HardwareSerial(ring_buffer *rx_buffer, ring_buffer *tx_buffer, + volatile uint8_t *ubrrh, volatile uint8_t *ubrrl, + volatile uint8_t *ucsra, volatile uint8_t *ucsrb, + volatile uint8_t *ucsrc, volatile uint8_t *udr, + uint8_t rxen, uint8_t txen, uint8_t rxcie, uint8_t udrie, uint8_t u2x); + void begin(unsigned long); + void begin(unsigned long, uint8_t); + void end(); + virtual int available(void); + virtual int peek(void); + virtual int read(void); + virtual void flush(void); + virtual size_t write(uint8_t); + inline size_t write(unsigned long n) { return write((uint8_t)n); } + inline size_t write(long n) { return write((uint8_t)n); } + inline size_t write(unsigned int n) { return write((uint8_t)n); } + inline size_t write(int n) { return write((uint8_t)n); } + using Print::write; // pull in write(str) and write(buf, size) from Print + operator bool(); +}; + +// Define config for Serial.begin(baud, config); +#define SERIAL_5N1 0x00 +#define SERIAL_6N1 0x02 +#define SERIAL_7N1 0x04 +#define SERIAL_8N1 0x06 +#define SERIAL_5N2 0x08 +#define SERIAL_6N2 0x0A +#define SERIAL_7N2 0x0C +#define SERIAL_8N2 0x0E +#define SERIAL_5E1 0x20 +#define SERIAL_6E1 0x22 +#define SERIAL_7E1 0x24 +#define SERIAL_8E1 0x26 +#define SERIAL_5E2 0x28 +#define SERIAL_6E2 0x2A +#define SERIAL_7E2 0x2C +#define SERIAL_8E2 0x2E +#define SERIAL_5O1 0x30 +#define SERIAL_6O1 0x32 +#define SERIAL_7O1 0x34 +#define SERIAL_8O1 0x36 +#define SERIAL_5O2 0x38 +#define SERIAL_6O2 0x3A +#define SERIAL_7O2 0x3C +#define SERIAL_8O2 0x3E + +#if defined(UBRRH) || defined(UBRR0H) + extern HardwareSerial Serial; +#elif defined(USBCON) + #include "USBAPI.h" +// extern HardwareSerial Serial_; +#endif +#if defined(UBRR1H) + extern HardwareSerial Serial1; +#endif +#if defined(UBRR2H) + extern HardwareSerial Serial2; +#endif +#if defined(UBRR3H) + extern HardwareSerial Serial3; +#endif + +extern void serialEventRun(void) __attribute__((weak)); + +#endif diff --git a/hardware/arduino/cores/robot/IPAddress.cpp b/hardware/arduino/cores/robot/IPAddress.cpp new file mode 100644 index 00000000000..353217237cd --- /dev/null +++ b/hardware/arduino/cores/robot/IPAddress.cpp @@ -0,0 +1,74 @@ +/* + IPAddress.cpp - Base class that provides IPAddress + Copyright (c) 2011 Adrian McEwen. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include +#include + +IPAddress::IPAddress() +{ + memset(_address, 0, sizeof(_address)); +} + +IPAddress::IPAddress(uint8_t first_octet, uint8_t second_octet, uint8_t third_octet, uint8_t fourth_octet) +{ + _address[0] = first_octet; + _address[1] = second_octet; + _address[2] = third_octet; + _address[3] = fourth_octet; +} + +IPAddress::IPAddress(uint32_t address) +{ + memcpy(_address, &address, sizeof(_address)); +} + +IPAddress::IPAddress(const uint8_t *address) +{ + memcpy(_address, address, sizeof(_address)); +} + +IPAddress& IPAddress::operator=(const uint8_t *address) +{ + memcpy(_address, address, sizeof(_address)); + return *this; +} + +IPAddress& IPAddress::operator=(uint32_t address) +{ + memcpy(_address, (const uint8_t *)&address, sizeof(_address)); + return *this; +} + +bool IPAddress::operator==(const uint8_t* addr) +{ + return memcmp(addr, _address, sizeof(_address)) == 0; +} + +size_t IPAddress::printTo(Print& p) const +{ + size_t n = 0; + for (int i =0; i < 3; i++) + { + n += p.print(_address[i], DEC); + n += p.print('.'); + } + n += p.print(_address[3], DEC); + return n; +} + diff --git a/hardware/arduino/cores/robot/IPAddress.h b/hardware/arduino/cores/robot/IPAddress.h new file mode 100644 index 00000000000..c2dd7e559d6 --- /dev/null +++ b/hardware/arduino/cores/robot/IPAddress.h @@ -0,0 +1,70 @@ +/* + IPAddress.h - Base class that provides IPAddress + Copyright (c) 2011 Adrian McEwen. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef IPAddress_h +#define IPAddress_h + +#include + +// A class to make it easier to handle and pass around IP addresses + +class IPAddress : public Printable { +private: + uint8_t _address[4]; // IPv4 address + // Access the raw byte array containing the address. Because this returns a pointer + // to the internal structure rather than a copy of the address this function should only + // be used when you know that the usage of the returned uint8_t* will be transient and not + // stored. + uint8_t* raw_address() { return _address; }; + +public: + // Constructors + IPAddress(); + IPAddress(uint8_t first_octet, uint8_t second_octet, uint8_t third_octet, uint8_t fourth_octet); + IPAddress(uint32_t address); + IPAddress(const uint8_t *address); + + // Overloaded cast operator to allow IPAddress objects to be used where a pointer + // to a four-byte uint8_t array is expected + operator uint32_t() { return *((uint32_t*)_address); }; + bool operator==(const IPAddress& addr) { return (*((uint32_t*)_address)) == (*((uint32_t*)addr._address)); }; + bool operator==(const uint8_t* addr); + + // Overloaded index operator to allow getting and setting individual octets of the address + uint8_t operator[](int index) const { return _address[index]; }; + uint8_t& operator[](int index) { return _address[index]; }; + + // Overloaded copy operators to allow initialisation of IPAddress objects from other types + IPAddress& operator=(const uint8_t *address); + IPAddress& operator=(uint32_t address); + + virtual size_t printTo(Print& p) const; + + friend class EthernetClass; + friend class UDP; + friend class Client; + friend class Server; + friend class DhcpClass; + friend class DNSClient; +}; + +const IPAddress INADDR_NONE(0,0,0,0); + + +#endif diff --git a/hardware/arduino/cores/robot/Platform.h b/hardware/arduino/cores/robot/Platform.h new file mode 100644 index 00000000000..8b8f742771a --- /dev/null +++ b/hardware/arduino/cores/robot/Platform.h @@ -0,0 +1,23 @@ + +#ifndef __PLATFORM_H__ +#define __PLATFORM_H__ + +#include +#include +#include +#include +#include + +typedef unsigned char u8; +typedef unsigned short u16; +typedef unsigned long u32; + +#include "Arduino.h" + +#if defined(USBCON) + #include "USBDesc.h" + #include "USBCore.h" + #include "USBAPI.h" +#endif /* if defined(USBCON) */ + +#endif diff --git a/hardware/arduino/cores/robot/Print.cpp b/hardware/arduino/cores/robot/Print.cpp new file mode 100755 index 00000000000..53961ec478c --- /dev/null +++ b/hardware/arduino/cores/robot/Print.cpp @@ -0,0 +1,268 @@ +/* + Print.cpp - Base class that provides print() and println() + Copyright (c) 2008 David A. Mellis. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Modified 23 November 2006 by David A. Mellis + */ + +#include +#include +#include +#include +#include "Arduino.h" + +#include "Print.h" + +// Public Methods ////////////////////////////////////////////////////////////// + +/* default implementation: may be overridden */ +size_t Print::write(const uint8_t *buffer, size_t size) +{ + size_t n = 0; + while (size--) { + n += write(*buffer++); + } + return n; +} + +size_t Print::print(const __FlashStringHelper *ifsh) +{ + const char PROGMEM *p = (const char PROGMEM *)ifsh; + size_t n = 0; + while (1) { + unsigned char c = pgm_read_byte(p++); + if (c == 0) break; + n += write(c); + } + return n; +} + +size_t Print::print(const String &s) +{ + size_t n = 0; + for (uint16_t i = 0; i < s.length(); i++) { + n += write(s[i]); + } + return n; +} + +size_t Print::print(const char str[]) +{ + return write(str); +} + +size_t Print::print(char c) +{ + return write(c); +} + +size_t Print::print(unsigned char b, int base) +{ + return print((unsigned long) b, base); +} + +size_t Print::print(int n, int base) +{ + return print((long) n, base); +} + +size_t Print::print(unsigned int n, int base) +{ + return print((unsigned long) n, base); +} + +size_t Print::print(long n, int base) +{ + if (base == 0) { + return write(n); + } else if (base == 10) { + if (n < 0) { + int t = print('-'); + n = -n; + return printNumber(n, 10) + t; + } + return printNumber(n, 10); + } else { + return printNumber(n, base); + } +} + +size_t Print::print(unsigned long n, int base) +{ + if (base == 0) return write(n); + else return printNumber(n, base); +} + +size_t Print::print(double n, int digits) +{ + return printFloat(n, digits); +} + +size_t Print::println(const __FlashStringHelper *ifsh) +{ + size_t n = print(ifsh); + n += println(); + return n; +} + +size_t Print::print(const Printable& x) +{ + return x.printTo(*this); +} + +size_t Print::println(void) +{ + size_t n = print('\r'); + n += print('\n'); + return n; +} + +size_t Print::println(const String &s) +{ + size_t n = print(s); + n += println(); + return n; +} + +size_t Print::println(const char c[]) +{ + size_t n = print(c); + n += println(); + return n; +} + +size_t Print::println(char c) +{ + size_t n = print(c); + n += println(); + return n; +} + +size_t Print::println(unsigned char b, int base) +{ + size_t n = print(b, base); + n += println(); + return n; +} + +size_t Print::println(int num, int base) +{ + size_t n = print(num, base); + n += println(); + return n; +} + +size_t Print::println(unsigned int num, int base) +{ + size_t n = print(num, base); + n += println(); + return n; +} + +size_t Print::println(long num, int base) +{ + size_t n = print(num, base); + n += println(); + return n; +} + +size_t Print::println(unsigned long num, int base) +{ + size_t n = print(num, base); + n += println(); + return n; +} + +size_t Print::println(double num, int digits) +{ + size_t n = print(num, digits); + n += println(); + return n; +} + +size_t Print::println(const Printable& x) +{ + size_t n = print(x); + n += println(); + return n; +} + +// Private Methods ///////////////////////////////////////////////////////////// + +size_t Print::printNumber(unsigned long n, uint8_t base) { + char buf[8 * sizeof(long) + 1]; // Assumes 8-bit chars plus zero byte. + char *str = &buf[sizeof(buf) - 1]; + + *str = '\0'; + + // prevent crash if called with base == 1 + if (base < 2) base = 10; + + do { + unsigned long m = n; + n /= base; + char c = m - base * n; + *--str = c < 10 ? c + '0' : c + 'A' - 10; + } while(n); + + return write(str); +} + +size_t Print::printFloat(double number, uint8_t digits) +{ + size_t n = 0; + + if (isnan(number)) return print("nan"); + if (isinf(number)) return print("inf"); + if (number > 4294967040.0) return print ("ovf"); // constant determined empirically + if (number <-4294967040.0) return print ("ovf"); // constant determined empirically + + // Handle negative numbers + if (number < 0.0) + { + n += print('-'); + number = -number; + } + + // Round correctly so that print(1.999, 2) prints as "2.00" + double rounding = 0.5; + for (uint8_t i=0; i 0) { + n += print("."); + } + + // Extract digits from the remainder one at a time + while (digits-- > 0) + { + remainder *= 10.0; + int toPrint = int(remainder); + n += print(toPrint); + remainder -= toPrint; + } + + return n; +} diff --git a/hardware/arduino/cores/robot/Print.h b/hardware/arduino/cores/robot/Print.h new file mode 100755 index 00000000000..dc76150871d --- /dev/null +++ b/hardware/arduino/cores/robot/Print.h @@ -0,0 +1,81 @@ +/* + Print.h - Base class that provides print() and println() + Copyright (c) 2008 David A. Mellis. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef Print_h +#define Print_h + +#include +#include // for size_t + +#include "WString.h" +#include "Printable.h" + +#define DEC 10 +#define HEX 16 +#define OCT 8 +#define BIN 2 + +class Print +{ + private: + int write_error; + size_t printNumber(unsigned long, uint8_t); + size_t printFloat(double, uint8_t); + protected: + void setWriteError(int err = 1) { write_error = err; } + public: + Print() : write_error(0) {} + + int getWriteError() { return write_error; } + void clearWriteError() { setWriteError(0); } + + virtual size_t write(uint8_t) = 0; + size_t write(const char *str) { + if (str == NULL) return 0; + return write((const uint8_t *)str, strlen(str)); + } + virtual size_t write(const uint8_t *buffer, size_t size); + + size_t print(const __FlashStringHelper *); + size_t print(const String &); + size_t print(const char[]); + size_t print(char); + size_t print(unsigned char, int = DEC); + size_t print(int, int = DEC); + size_t print(unsigned int, int = DEC); + size_t print(long, int = DEC); + size_t print(unsigned long, int = DEC); + size_t print(double, int = 2); + size_t print(const Printable&); + + size_t println(const __FlashStringHelper *); + size_t println(const String &s); + size_t println(const char[]); + size_t println(char); + size_t println(unsigned char, int = DEC); + size_t println(int, int = DEC); + size_t println(unsigned int, int = DEC); + size_t println(long, int = DEC); + size_t println(unsigned long, int = DEC); + size_t println(double, int = 2); + size_t println(const Printable&); + size_t println(void); +}; + +#endif diff --git a/hardware/arduino/cores/robot/Printable.h b/hardware/arduino/cores/robot/Printable.h new file mode 100644 index 00000000000..d03c9af62c4 --- /dev/null +++ b/hardware/arduino/cores/robot/Printable.h @@ -0,0 +1,40 @@ +/* + Printable.h - Interface class that allows printing of complex types + Copyright (c) 2011 Adrian McEwen. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef Printable_h +#define Printable_h + +#include + +class Print; + +/** The Printable class provides a way for new classes to allow themselves to be printed. + By deriving from Printable and implementing the printTo method, it will then be possible + for users to print out instances of this class by passing them into the usual + Print::print and Print::println methods. +*/ + +class Printable +{ + public: + virtual size_t printTo(Print& p) const = 0; +}; + +#endif + diff --git a/hardware/arduino/cores/robot/Server.h b/hardware/arduino/cores/robot/Server.h new file mode 100644 index 00000000000..77c415cce06 --- /dev/null +++ b/hardware/arduino/cores/robot/Server.h @@ -0,0 +1,28 @@ +/* + Server.h - Base class that provides Server + Copyright (c) 2011 Adrian McEwen. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef server_h +#define server_h + +class Server : public Print { +public: + virtual void begin() =0; +}; + +#endif diff --git a/hardware/arduino/cores/robot/Stream.cpp b/hardware/arduino/cores/robot/Stream.cpp new file mode 100644 index 00000000000..aafb7fcf97d --- /dev/null +++ b/hardware/arduino/cores/robot/Stream.cpp @@ -0,0 +1,270 @@ +/* + Stream.cpp - adds parsing methods to Stream class + Copyright (c) 2008 David A. Mellis. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Created July 2011 + parsing functions based on TextFinder library by Michael Margolis + */ + +#include "Arduino.h" +#include "Stream.h" + +#define PARSE_TIMEOUT 1000 // default number of milli-seconds to wait +#define NO_SKIP_CHAR 1 // a magic char not found in a valid ASCII numeric field + +// private method to read stream with timeout +int Stream::timedRead() +{ + int c; + _startMillis = millis(); + do { + c = read(); + if (c >= 0) return c; + } while(millis() - _startMillis < _timeout); + return -1; // -1 indicates timeout +} + +// private method to peek stream with timeout +int Stream::timedPeek() +{ + int c; + _startMillis = millis(); + do { + c = peek(); + if (c >= 0) return c; + } while(millis() - _startMillis < _timeout); + return -1; // -1 indicates timeout +} + +// returns peek of the next digit in the stream or -1 if timeout +// discards non-numeric characters +int Stream::peekNextDigit() +{ + int c; + while (1) { + c = timedPeek(); + if (c < 0) return c; // timeout + if (c == '-') return c; + if (c >= '0' && c <= '9') return c; + read(); // discard non-numeric + } +} + +// Public Methods +////////////////////////////////////////////////////////////// + +void Stream::setTimeout(unsigned long timeout) // sets the maximum number of milliseconds to wait +{ + _timeout = timeout; +} + + // find returns true if the target string is found +bool Stream::find(char *target) +{ + return findUntil(target, NULL); +} + +// reads data from the stream until the target string of given length is found +// returns true if target string is found, false if timed out +bool Stream::find(char *target, size_t length) +{ + return findUntil(target, length, NULL, 0); +} + +// as find but search ends if the terminator string is found +bool Stream::findUntil(char *target, char *terminator) +{ + return findUntil(target, strlen(target), terminator, strlen(terminator)); +} + +// reads data from the stream until the target string of the given length is found +// search terminated if the terminator string is found +// returns true if target string is found, false if terminated or timed out +bool Stream::findUntil(char *target, size_t targetLen, char *terminator, size_t termLen) +{ + size_t index = 0; // maximum target string length is 64k bytes! + size_t termIndex = 0; + int c; + + if( *target == 0) + return true; // return true if target is a null string + while( (c = timedRead()) > 0){ + + if(c != target[index]) + index = 0; // reset index if any char does not match + + if( c == target[index]){ + //////Serial.print("found "); Serial.write(c); Serial.print("index now"); Serial.println(index+1); + if(++index >= targetLen){ // return true if all chars in the target match + return true; + } + } + + if(termLen > 0 && c == terminator[termIndex]){ + if(++termIndex >= termLen) + return false; // return false if terminate string found before target string + } + else + termIndex = 0; + } + return false; +} + + +// returns the first valid (long) integer value from the current position. +// initial characters that are not digits (or the minus sign) are skipped +// function is terminated by the first character that is not a digit. +long Stream::parseInt() +{ + return parseInt(NO_SKIP_CHAR); // terminate on first non-digit character (or timeout) +} + +// as above but a given skipChar is ignored +// this allows format characters (typically commas) in values to be ignored +long Stream::parseInt(char skipChar) +{ + boolean isNegative = false; + long value = 0; + int c; + + c = peekNextDigit(); + // ignore non numeric leading characters + if(c < 0) + return 0; // zero returned if timeout + + do{ + if(c == skipChar) + ; // ignore this charactor + else if(c == '-') + isNegative = true; + else if(c >= '0' && c <= '9') // is c a digit? + value = value * 10 + c - '0'; + read(); // consume the character we got with peek + c = timedPeek(); + } + while( (c >= '0' && c <= '9') || c == skipChar ); + + if(isNegative) + value = -value; + return value; +} + + +// as parseInt but returns a floating point value +float Stream::parseFloat() +{ + return parseFloat(NO_SKIP_CHAR); +} + +// as above but the given skipChar is ignored +// this allows format characters (typically commas) in values to be ignored +float Stream::parseFloat(char skipChar){ + boolean isNegative = false; + boolean isFraction = false; + long value = 0; + char c; + float fraction = 1.0; + + c = peekNextDigit(); + // ignore non numeric leading characters + if(c < 0) + return 0; // zero returned if timeout + + do{ + if(c == skipChar) + ; // ignore + else if(c == '-') + isNegative = true; + else if (c == '.') + isFraction = true; + else if(c >= '0' && c <= '9') { // is c a digit? + value = value * 10 + c - '0'; + if(isFraction) + fraction *= 0.1; + } + read(); // consume the character we got with peek + c = timedPeek(); + } + while( (c >= '0' && c <= '9') || c == '.' || c == skipChar ); + + if(isNegative) + value = -value; + if(isFraction) + return value * fraction; + else + return value; +} + +// read characters from stream into buffer +// terminates if length characters have been read, or timeout (see setTimeout) +// returns the number of characters placed in the buffer +// the buffer is NOT null terminated. +// +size_t Stream::readBytes(char *buffer, size_t length) +{ + size_t count = 0; + while (count < length) { + int c = timedRead(); + if (c < 0) break; + *buffer++ = (char)c; + count++; + } + return count; +} + + +// as readBytes with terminator character +// terminates if length characters have been read, timeout, or if the terminator character detected +// returns the number of characters placed in the buffer (0 means no valid data found) + +size_t Stream::readBytesUntil(char terminator, char *buffer, size_t length) +{ + if (length < 1) return 0; + size_t index = 0; + while (index < length) { + int c = timedRead(); + if (c < 0 || c == terminator) break; + *buffer++ = (char)c; + index++; + } + return index; // return number of characters, not including null terminator +} + +String Stream::readString() +{ + String ret; + int c = timedRead(); + while (c >= 0) + { + ret += (char)c; + c = timedRead(); + } + return ret; +} + +String Stream::readStringUntil(char terminator) +{ + String ret; + int c = timedRead(); + while (c >= 0 && c != terminator) + { + ret += (char)c; + c = timedRead(); + } + return ret; +} + diff --git a/hardware/arduino/cores/robot/Stream.h b/hardware/arduino/cores/robot/Stream.h new file mode 100644 index 00000000000..007b4bc66c7 --- /dev/null +++ b/hardware/arduino/cores/robot/Stream.h @@ -0,0 +1,96 @@ +/* + Stream.h - base class for character-based streams. + Copyright (c) 2010 David A. Mellis. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + parsing functions based on TextFinder library by Michael Margolis +*/ + +#ifndef Stream_h +#define Stream_h + +#include +#include "Print.h" + +// compatability macros for testing +/* +#define getInt() parseInt() +#define getInt(skipChar) parseInt(skipchar) +#define getFloat() parseFloat() +#define getFloat(skipChar) parseFloat(skipChar) +#define getString( pre_string, post_string, buffer, length) +readBytesBetween( pre_string, terminator, buffer, length) +*/ + +class Stream : public Print +{ + protected: + unsigned long _timeout; // number of milliseconds to wait for the next char before aborting timed read + unsigned long _startMillis; // used for timeout measurement + int timedRead(); // private method to read stream with timeout + int timedPeek(); // private method to peek stream with timeout + int peekNextDigit(); // returns the next numeric digit in the stream or -1 if timeout + + public: + virtual int available() = 0; + virtual int read() = 0; + virtual int peek() = 0; + virtual void flush() = 0; + + Stream() {_timeout=1000;} + +// parsing methods + + void setTimeout(unsigned long timeout); // sets maximum milliseconds to wait for stream data, default is 1 second + + bool find(char *target); // reads data from the stream until the target string is found + // returns true if target string is found, false if timed out (see setTimeout) + + bool find(char *target, size_t length); // reads data from the stream until the target string of given length is found + // returns true if target string is found, false if timed out + + bool findUntil(char *target, char *terminator); // as find but search ends if the terminator string is found + + bool findUntil(char *target, size_t targetLen, char *terminate, size_t termLen); // as above but search ends if the terminate string is found + + + long parseInt(); // returns the first valid (long) integer value from the current position. + // initial characters that are not digits (or the minus sign) are skipped + // integer is terminated by the first character that is not a digit. + + float parseFloat(); // float version of parseInt + + size_t readBytes( char *buffer, size_t length); // read chars from stream into buffer + // terminates if length characters have been read or timeout (see setTimeout) + // returns the number of characters placed in the buffer (0 means no valid data found) + + size_t readBytesUntil( char terminator, char *buffer, size_t length); // as readBytes with terminator character + // terminates if length characters have been read, timeout, or if the terminator character detected + // returns the number of characters placed in the buffer (0 means no valid data found) + + // Arduino String functions to be added here + String readString(); + String readStringUntil(char terminator); + + protected: + long parseInt(char skipChar); // as above but the given skipChar is ignored + // as above but the given skipChar is ignored + // this allows format characters (typically commas) in values to be ignored + + float parseFloat(char skipChar); // as above but the given skipChar is ignored +}; + +#endif diff --git a/hardware/arduino/cores/robot/Tone.cpp b/hardware/arduino/cores/robot/Tone.cpp new file mode 100755 index 00000000000..9bb6fe721c6 --- /dev/null +++ b/hardware/arduino/cores/robot/Tone.cpp @@ -0,0 +1,616 @@ +/* Tone.cpp + + A Tone Generator Library + + Written by Brett Hagman + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +Version Modified By Date Comments +------- ----------- -------- -------- +0001 B Hagman 09/08/02 Initial coding +0002 B Hagman 09/08/18 Multiple pins +0003 B Hagman 09/08/18 Moved initialization from constructor to begin() +0004 B Hagman 09/09/26 Fixed problems with ATmega8 +0005 B Hagman 09/11/23 Scanned prescalars for best fit on 8 bit timers + 09/11/25 Changed pin toggle method to XOR + 09/11/25 Fixed timer0 from being excluded +0006 D Mellis 09/12/29 Replaced objects with functions +0007 M Sproul 10/08/29 Changed #ifdefs from cpu to register +0008 S Kanemoto 12/06/22 Fixed for Leonardo by @maris_HY +*************************************************/ + +#include +#include +#include "Arduino.h" +#include "pins_arduino.h" + +#if defined(__AVR_ATmega8__) || defined(__AVR_ATmega128__) +#define TCCR2A TCCR2 +#define TCCR2B TCCR2 +#define COM2A1 COM21 +#define COM2A0 COM20 +#define OCR2A OCR2 +#define TIMSK2 TIMSK +#define OCIE2A OCIE2 +#define TIMER2_COMPA_vect TIMER2_COMP_vect +#define TIMSK1 TIMSK +#endif + +// timerx_toggle_count: +// > 0 - duration specified +// = 0 - stopped +// < 0 - infinitely (until stop() method called, or new play() called) + +#if !defined(__AVR_ATmega8__) +volatile long timer0_toggle_count; +volatile uint8_t *timer0_pin_port; +volatile uint8_t timer0_pin_mask; +#endif + +volatile long timer1_toggle_count; +volatile uint8_t *timer1_pin_port; +volatile uint8_t timer1_pin_mask; +volatile long timer2_toggle_count; +volatile uint8_t *timer2_pin_port; +volatile uint8_t timer2_pin_mask; + +#if defined(TIMSK3) +volatile long timer3_toggle_count; +volatile uint8_t *timer3_pin_port; +volatile uint8_t timer3_pin_mask; +#endif + +#if defined(TIMSK4) +volatile long timer4_toggle_count; +volatile uint8_t *timer4_pin_port; +volatile uint8_t timer4_pin_mask; +#endif + +#if defined(TIMSK5) +volatile long timer5_toggle_count; +volatile uint8_t *timer5_pin_port; +volatile uint8_t timer5_pin_mask; +#endif + + +#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) + +#define AVAILABLE_TONE_PINS 1 +#define USE_TIMER2 + +const uint8_t PROGMEM tone_pin_to_timer_PGM[] = { 2 /*, 3, 4, 5, 1, 0 */ }; +static uint8_t tone_pins[AVAILABLE_TONE_PINS] = { 255 /*, 255, 255, 255, 255, 255 */ }; + +#elif defined(__AVR_ATmega8__) + +#define AVAILABLE_TONE_PINS 1 +#define USE_TIMER2 + +const uint8_t PROGMEM tone_pin_to_timer_PGM[] = { 2 /*, 1 */ }; +static uint8_t tone_pins[AVAILABLE_TONE_PINS] = { 255 /*, 255 */ }; + +#elif defined(__AVR_ATmega32U4__) + +#define AVAILABLE_TONE_PINS 1 +#define USE_TIMER3 + +const uint8_t PROGMEM tone_pin_to_timer_PGM[] = { 3 /*, 1 */ }; +static uint8_t tone_pins[AVAILABLE_TONE_PINS] = { 255 /*, 255 */ }; + +#else + +#define AVAILABLE_TONE_PINS 1 +#define USE_TIMER2 + +// Leave timer 0 to last. +const uint8_t PROGMEM tone_pin_to_timer_PGM[] = { 2 /*, 1, 0 */ }; +static uint8_t tone_pins[AVAILABLE_TONE_PINS] = { 255 /*, 255, 255 */ }; + +#endif + + + +static int8_t toneBegin(uint8_t _pin) +{ + int8_t _timer = -1; + + // if we're already using the pin, the timer should be configured. + for (int i = 0; i < AVAILABLE_TONE_PINS; i++) { + if (tone_pins[i] == _pin) { + return pgm_read_byte(tone_pin_to_timer_PGM + i); + } + } + + // search for an unused timer. + for (int i = 0; i < AVAILABLE_TONE_PINS; i++) { + if (tone_pins[i] == 255) { + tone_pins[i] = _pin; + _timer = pgm_read_byte(tone_pin_to_timer_PGM + i); + break; + } + } + + if (_timer != -1) + { + // Set timer specific stuff + // All timers in CTC mode + // 8 bit timers will require changing prescalar values, + // whereas 16 bit timers are set to either ck/1 or ck/64 prescalar + switch (_timer) + { + #if defined(TCCR0A) && defined(TCCR0B) + case 0: + // 8 bit timer + TCCR0A = 0; + TCCR0B = 0; + bitWrite(TCCR0A, WGM01, 1); + bitWrite(TCCR0B, CS00, 1); + timer0_pin_port = portOutputRegister(digitalPinToPort(_pin)); + timer0_pin_mask = digitalPinToBitMask(_pin); + break; + #endif + + #if defined(TCCR1A) && defined(TCCR1B) && defined(WGM12) + case 1: + // 16 bit timer + TCCR1A = 0; + TCCR1B = 0; + bitWrite(TCCR1B, WGM12, 1); + bitWrite(TCCR1B, CS10, 1); + timer1_pin_port = portOutputRegister(digitalPinToPort(_pin)); + timer1_pin_mask = digitalPinToBitMask(_pin); + break; + #endif + + #if defined(TCCR2A) && defined(TCCR2B) + case 2: + // 8 bit timer + TCCR2A = 0; + TCCR2B = 0; + bitWrite(TCCR2A, WGM21, 1); + bitWrite(TCCR2B, CS20, 1); + timer2_pin_port = portOutputRegister(digitalPinToPort(_pin)); + timer2_pin_mask = digitalPinToBitMask(_pin); + break; + #endif + + #if defined(TCCR3A) && defined(TCCR3B) && defined(TIMSK3) + case 3: + // 16 bit timer + TCCR3A = 0; + TCCR3B = 0; + bitWrite(TCCR3B, WGM32, 1); + bitWrite(TCCR3B, CS30, 1); + timer3_pin_port = portOutputRegister(digitalPinToPort(_pin)); + timer3_pin_mask = digitalPinToBitMask(_pin); + break; + #endif + + #if defined(TCCR4A) && defined(TCCR4B) && defined(TIMSK4) + case 4: + // 16 bit timer + TCCR4A = 0; + TCCR4B = 0; + #if defined(WGM42) + bitWrite(TCCR4B, WGM42, 1); + #elif defined(CS43) + #warning this may not be correct + // atmega32u4 + bitWrite(TCCR4B, CS43, 1); + #endif + bitWrite(TCCR4B, CS40, 1); + timer4_pin_port = portOutputRegister(digitalPinToPort(_pin)); + timer4_pin_mask = digitalPinToBitMask(_pin); + break; + #endif + + #if defined(TCCR5A) && defined(TCCR5B) && defined(TIMSK5) + case 5: + // 16 bit timer + TCCR5A = 0; + TCCR5B = 0; + bitWrite(TCCR5B, WGM52, 1); + bitWrite(TCCR5B, CS50, 1); + timer5_pin_port = portOutputRegister(digitalPinToPort(_pin)); + timer5_pin_mask = digitalPinToBitMask(_pin); + break; + #endif + } + } + + return _timer; +} + + + +// frequency (in hertz) and duration (in milliseconds). + +void tone(uint8_t _pin, unsigned int frequency, unsigned long duration) +{ + uint8_t prescalarbits = 0b001; + long toggle_count = 0; + uint32_t ocr = 0; + int8_t _timer; + + _timer = toneBegin(_pin); + + if (_timer >= 0) + { + // Set the pinMode as OUTPUT + pinMode(_pin, OUTPUT); + + // if we are using an 8 bit timer, scan through prescalars to find the best fit + if (_timer == 0 || _timer == 2) + { + ocr = F_CPU / frequency / 2 - 1; + prescalarbits = 0b001; // ck/1: same for both timers + if (ocr > 255) + { + ocr = F_CPU / frequency / 2 / 8 - 1; + prescalarbits = 0b010; // ck/8: same for both timers + + if (_timer == 2 && ocr > 255) + { + ocr = F_CPU / frequency / 2 / 32 - 1; + prescalarbits = 0b011; + } + + if (ocr > 255) + { + ocr = F_CPU / frequency / 2 / 64 - 1; + prescalarbits = _timer == 0 ? 0b011 : 0b100; + + if (_timer == 2 && ocr > 255) + { + ocr = F_CPU / frequency / 2 / 128 - 1; + prescalarbits = 0b101; + } + + if (ocr > 255) + { + ocr = F_CPU / frequency / 2 / 256 - 1; + prescalarbits = _timer == 0 ? 0b100 : 0b110; + if (ocr > 255) + { + // can't do any better than /1024 + ocr = F_CPU / frequency / 2 / 1024 - 1; + prescalarbits = _timer == 0 ? 0b101 : 0b111; + } + } + } + } + +#if defined(TCCR0B) + if (_timer == 0) + { + TCCR0B = prescalarbits; + } + else +#endif +#if defined(TCCR2B) + { + TCCR2B = prescalarbits; + } +#else + { + // dummy place holder to make the above ifdefs work + } +#endif + } + else + { + // two choices for the 16 bit timers: ck/1 or ck/64 + ocr = F_CPU / frequency / 2 - 1; + + prescalarbits = 0b001; + if (ocr > 0xffff) + { + ocr = F_CPU / frequency / 2 / 64 - 1; + prescalarbits = 0b011; + } + + if (_timer == 1) + { +#if defined(TCCR1B) + TCCR1B = (TCCR1B & 0b11111000) | prescalarbits; +#endif + } +#if defined(TCCR3B) + else if (_timer == 3) + TCCR3B = (TCCR3B & 0b11111000) | prescalarbits; +#endif +#if defined(TCCR4B) + else if (_timer == 4) + TCCR4B = (TCCR4B & 0b11111000) | prescalarbits; +#endif +#if defined(TCCR5B) + else if (_timer == 5) + TCCR5B = (TCCR5B & 0b11111000) | prescalarbits; +#endif + + } + + + // Calculate the toggle count + if (duration > 0) + { + toggle_count = 2 * frequency * duration / 1000; + } + else + { + toggle_count = -1; + } + + // Set the OCR for the given timer, + // set the toggle count, + // then turn on the interrupts + switch (_timer) + { + +#if defined(OCR0A) && defined(TIMSK0) && defined(OCIE0A) + case 0: + OCR0A = ocr; + timer0_toggle_count = toggle_count; + bitWrite(TIMSK0, OCIE0A, 1); + break; +#endif + + case 1: +#if defined(OCR1A) && defined(TIMSK1) && defined(OCIE1A) + OCR1A = ocr; + timer1_toggle_count = toggle_count; + bitWrite(TIMSK1, OCIE1A, 1); +#elif defined(OCR1A) && defined(TIMSK) && defined(OCIE1A) + // this combination is for at least the ATmega32 + OCR1A = ocr; + timer1_toggle_count = toggle_count; + bitWrite(TIMSK, OCIE1A, 1); +#endif + break; + +#if defined(OCR2A) && defined(TIMSK2) && defined(OCIE2A) + case 2: + OCR2A = ocr; + timer2_toggle_count = toggle_count; + bitWrite(TIMSK2, OCIE2A, 1); + break; +#endif + +#if defined(TIMSK3) + case 3: + OCR3A = ocr; + timer3_toggle_count = toggle_count; + bitWrite(TIMSK3, OCIE3A, 1); + break; +#endif + +#if defined(TIMSK4) + case 4: + OCR4A = ocr; + timer4_toggle_count = toggle_count; + bitWrite(TIMSK4, OCIE4A, 1); + break; +#endif + +#if defined(OCR5A) && defined(TIMSK5) && defined(OCIE5A) + case 5: + OCR5A = ocr; + timer5_toggle_count = toggle_count; + bitWrite(TIMSK5, OCIE5A, 1); + break; +#endif + + } + } +} + + +// XXX: this function only works properly for timer 2 (the only one we use +// currently). for the others, it should end the tone, but won't restore +// proper PWM functionality for the timer. +void disableTimer(uint8_t _timer) +{ + switch (_timer) + { + case 0: + #if defined(TIMSK0) + TIMSK0 = 0; + #elif defined(TIMSK) + TIMSK = 0; // atmega32 + #endif + break; + +#if defined(TIMSK1) && defined(OCIE1A) + case 1: + bitWrite(TIMSK1, OCIE1A, 0); + break; +#endif + + case 2: + #if defined(TIMSK2) && defined(OCIE2A) + bitWrite(TIMSK2, OCIE2A, 0); // disable interrupt + #endif + #if defined(TCCR2A) && defined(WGM20) + TCCR2A = (1 << WGM20); + #endif + #if defined(TCCR2B) && defined(CS22) + TCCR2B = (TCCR2B & 0b11111000) | (1 << CS22); + #endif + #if defined(OCR2A) + OCR2A = 0; + #endif + break; + +#if defined(TIMSK3) + case 3: + TIMSK3 = 0; + break; +#endif + +#if defined(TIMSK4) + case 4: + TIMSK4 = 0; + break; +#endif + +#if defined(TIMSK5) + case 5: + TIMSK5 = 0; + break; +#endif + } +} + + +void noTone(uint8_t _pin) +{ + int8_t _timer = -1; + + for (int i = 0; i < AVAILABLE_TONE_PINS; i++) { + if (tone_pins[i] == _pin) { + _timer = pgm_read_byte(tone_pin_to_timer_PGM + i); + tone_pins[i] = 255; + } + } + + disableTimer(_timer); + + digitalWrite(_pin, 0); +} + +#ifdef USE_TIMER0 +ISR(TIMER0_COMPA_vect) +{ + if (timer0_toggle_count != 0) + { + // toggle the pin + *timer0_pin_port ^= timer0_pin_mask; + + if (timer0_toggle_count > 0) + timer0_toggle_count--; + } + else + { + disableTimer(0); + *timer0_pin_port &= ~(timer0_pin_mask); // keep pin low after stop + } +} +#endif + + +#ifdef USE_TIMER1 +ISR(TIMER1_COMPA_vect) +{ + if (timer1_toggle_count != 0) + { + // toggle the pin + *timer1_pin_port ^= timer1_pin_mask; + + if (timer1_toggle_count > 0) + timer1_toggle_count--; + } + else + { + disableTimer(1); + *timer1_pin_port &= ~(timer1_pin_mask); // keep pin low after stop + } +} +#endif + + +#ifdef USE_TIMER2 +ISR(TIMER2_COMPA_vect) +{ + + if (timer2_toggle_count != 0) + { + // toggle the pin + *timer2_pin_port ^= timer2_pin_mask; + + if (timer2_toggle_count > 0) + timer2_toggle_count--; + } + else + { + // need to call noTone() so that the tone_pins[] entry is reset, so the + // timer gets initialized next time we call tone(). + // XXX: this assumes timer 2 is always the first one used. + noTone(tone_pins[0]); +// disableTimer(2); +// *timer2_pin_port &= ~(timer2_pin_mask); // keep pin low after stop + } +} +#endif + + +#ifdef USE_TIMER3 +ISR(TIMER3_COMPA_vect) +{ + if (timer3_toggle_count != 0) + { + // toggle the pin + *timer3_pin_port ^= timer3_pin_mask; + + if (timer3_toggle_count > 0) + timer3_toggle_count--; + } + else + { + disableTimer(3); + *timer3_pin_port &= ~(timer3_pin_mask); // keep pin low after stop + } +} +#endif + + +#ifdef USE_TIMER4 +ISR(TIMER4_COMPA_vect) +{ + if (timer4_toggle_count != 0) + { + // toggle the pin + *timer4_pin_port ^= timer4_pin_mask; + + if (timer4_toggle_count > 0) + timer4_toggle_count--; + } + else + { + disableTimer(4); + *timer4_pin_port &= ~(timer4_pin_mask); // keep pin low after stop + } +} +#endif + + +#ifdef USE_TIMER5 +ISR(TIMER5_COMPA_vect) +{ + if (timer5_toggle_count != 0) + { + // toggle the pin + *timer5_pin_port ^= timer5_pin_mask; + + if (timer5_toggle_count > 0) + timer5_toggle_count--; + } + else + { + disableTimer(5); + *timer5_pin_port &= ~(timer5_pin_mask); // keep pin low after stop + } +} +#endif diff --git a/hardware/arduino/cores/robot/USBAPI.h b/hardware/arduino/cores/robot/USBAPI.h new file mode 100644 index 00000000000..eb2e5937db0 --- /dev/null +++ b/hardware/arduino/cores/robot/USBAPI.h @@ -0,0 +1,196 @@ + + +#ifndef __USBAPI__ +#define __USBAPI__ + +#if defined(USBCON) + +//================================================================================ +//================================================================================ +// USB + +class USBDevice_ +{ +public: + USBDevice_(); + bool configured(); + + void attach(); + void detach(); // Serial port goes down too... + void poll(); +}; +extern USBDevice_ USBDevice; + +//================================================================================ +//================================================================================ +// Serial over CDC (Serial1 is the physical port) + +class Serial_ : public Stream +{ +private: + ring_buffer *_cdc_rx_buffer; +public: + void begin(uint16_t baud_count); + void end(void); + + virtual int available(void); + virtual void accept(void); + virtual int peek(void); + virtual int read(void); + virtual void flush(void); + virtual size_t write(uint8_t); + using Print::write; // pull in write(str) and write(buf, size) from Print + operator bool(); +}; +extern Serial_ Serial; + +//================================================================================ +//================================================================================ +// Mouse + +#define MOUSE_LEFT 1 +#define MOUSE_RIGHT 2 +#define MOUSE_MIDDLE 4 +#define MOUSE_ALL (MOUSE_LEFT | MOUSE_RIGHT | MOUSE_MIDDLE) + +class Mouse_ +{ +private: + uint8_t _buttons; + void buttons(uint8_t b); +public: + Mouse_(void); + void begin(void); + void end(void); + void click(uint8_t b = MOUSE_LEFT); + void move(signed char x, signed char y, signed char wheel = 0); + void press(uint8_t b = MOUSE_LEFT); // press LEFT by default + void release(uint8_t b = MOUSE_LEFT); // release LEFT by default + bool isPressed(uint8_t b = MOUSE_LEFT); // check LEFT by default +}; +extern Mouse_ Mouse; + +//================================================================================ +//================================================================================ +// Keyboard + +#define KEY_LEFT_CTRL 0x80 +#define KEY_LEFT_SHIFT 0x81 +#define KEY_LEFT_ALT 0x82 +#define KEY_LEFT_GUI 0x83 +#define KEY_RIGHT_CTRL 0x84 +#define KEY_RIGHT_SHIFT 0x85 +#define KEY_RIGHT_ALT 0x86 +#define KEY_RIGHT_GUI 0x87 + +#define KEY_UP_ARROW 0xDA +#define KEY_DOWN_ARROW 0xD9 +#define KEY_LEFT_ARROW 0xD8 +#define KEY_RIGHT_ARROW 0xD7 +#define KEY_BACKSPACE 0xB2 +#define KEY_TAB 0xB3 +#define KEY_RETURN 0xB0 +#define KEY_ESC 0xB1 +#define KEY_INSERT 0xD1 +#define KEY_DELETE 0xD4 +#define KEY_PAGE_UP 0xD3 +#define KEY_PAGE_DOWN 0xD6 +#define KEY_HOME 0xD2 +#define KEY_END 0xD5 +#define KEY_CAPS_LOCK 0xC1 +#define KEY_F1 0xC2 +#define KEY_F2 0xC3 +#define KEY_F3 0xC4 +#define KEY_F4 0xC5 +#define KEY_F5 0xC6 +#define KEY_F6 0xC7 +#define KEY_F7 0xC8 +#define KEY_F8 0xC9 +#define KEY_F9 0xCA +#define KEY_F10 0xCB +#define KEY_F11 0xCC +#define KEY_F12 0xCD + +// Low level key report: up to 6 keys and shift, ctrl etc at once +typedef struct +{ + uint8_t modifiers; + uint8_t reserved; + uint8_t keys[6]; +} KeyReport; + +class Keyboard_ : public Print +{ +private: + KeyReport _keyReport; + void sendReport(KeyReport* keys); +public: + Keyboard_(void); + void begin(void); + void end(void); + virtual size_t write(uint8_t k); + virtual size_t press(uint8_t k); + virtual size_t release(uint8_t k); + virtual void releaseAll(void); +}; +extern Keyboard_ Keyboard; + +//================================================================================ +//================================================================================ +// Low level API + +typedef struct +{ + uint8_t bmRequestType; + uint8_t bRequest; + uint8_t wValueL; + uint8_t wValueH; + uint16_t wIndex; + uint16_t wLength; +} Setup; + +//================================================================================ +//================================================================================ +// HID 'Driver' + +int HID_GetInterface(uint8_t* interfaceNum); +int HID_GetDescriptor(int i); +bool HID_Setup(Setup& setup); +void HID_SendReport(uint8_t id, const void* data, int len); + +//================================================================================ +//================================================================================ +// MSC 'Driver' + +int MSC_GetInterface(uint8_t* interfaceNum); +int MSC_GetDescriptor(int i); +bool MSC_Setup(Setup& setup); +bool MSC_Data(uint8_t rx,uint8_t tx); + +//================================================================================ +//================================================================================ +// CSC 'Driver' + +int CDC_GetInterface(uint8_t* interfaceNum); +int CDC_GetDescriptor(int i); +bool CDC_Setup(Setup& setup); + +//================================================================================ +//================================================================================ + +#define TRANSFER_PGM 0x80 +#define TRANSFER_RELEASE 0x40 +#define TRANSFER_ZERO 0x20 + +int USB_SendControl(uint8_t flags, const void* d, int len); +int USB_RecvControl(void* d, int len); + +uint8_t USB_Available(uint8_t ep); +int USB_Send(uint8_t ep, const void* data, int len); // blocking +int USB_Recv(uint8_t ep, void* data, int len); // non-blocking +int USB_Recv(uint8_t ep); // non-blocking +void USB_Flush(uint8_t ep); + +#endif + +#endif /* if defined(USBCON) */ \ No newline at end of file diff --git a/hardware/arduino/cores/robot/USBCore.cpp b/hardware/arduino/cores/robot/USBCore.cpp new file mode 100644 index 00000000000..d3e01706567 --- /dev/null +++ b/hardware/arduino/cores/robot/USBCore.cpp @@ -0,0 +1,684 @@ + + +/* Copyright (c) 2010, Peter Barrett +** +** Permission to use, copy, modify, and/or distribute this software for +** any purpose with or without fee is hereby granted, provided that the +** above copyright notice and this permission notice appear in all copies. +** +** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL +** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED +** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR +** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES +** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS +** SOFTWARE. +*/ + +#include "Platform.h" +#include "USBAPI.h" +#include "USBDesc.h" + +#if defined(USBCON) + +#define EP_TYPE_CONTROL 0x00 +#define EP_TYPE_BULK_IN 0x81 +#define EP_TYPE_BULK_OUT 0x80 +#define EP_TYPE_INTERRUPT_IN 0xC1 +#define EP_TYPE_INTERRUPT_OUT 0xC0 +#define EP_TYPE_ISOCHRONOUS_IN 0x41 +#define EP_TYPE_ISOCHRONOUS_OUT 0x40 + +/** Pulse generation counters to keep track of the number of milliseconds remaining for each pulse type */ +#define TX_RX_LED_PULSE_MS 100 +volatile u8 TxLEDPulse; /**< Milliseconds remaining for data Tx LED pulse */ +volatile u8 RxLEDPulse; /**< Milliseconds remaining for data Rx LED pulse */ + +//================================================================== +//================================================================== + +extern const u16 STRING_LANGUAGE[] PROGMEM; +extern const u16 STRING_IPRODUCT[] PROGMEM; +extern const u16 STRING_IMANUFACTURER[] PROGMEM; +extern const DeviceDescriptor USB_DeviceDescriptor PROGMEM; +extern const DeviceDescriptor USB_DeviceDescriptorA PROGMEM; + +const u16 STRING_LANGUAGE[2] = { + (3<<8) | (2+2), + 0x0409 // English +}; + +const u16 STRING_IPRODUCT[17] = { + (3<<8) | (2+2*16), +#if USB_PID == 0x8036 + 'A','r','d','u','i','n','o',' ','L','e','o','n','a','r','d','o' +#elif USB_PID == 0x8037 + 'A','r','d','u','i','n','o',' ','M','i','c','r','o',' ',' ',' ' +#elif USB_PID == 0x803C + 'A','r','d','u','i','n','o',' ','E','s','p','l','o','r','a',' ' +#elif USB_PID == 0x9208 + 'L','i','l','y','P','a','d','U','S','B',' ',' ',' ',' ',' ',' ' +#else + 'U','S','B',' ','I','O',' ','B','o','a','r','d',' ',' ',' ',' ' +#endif +}; + +const u16 STRING_IMANUFACTURER[12] = { + (3<<8) | (2+2*11), +#if USB_VID == 0x2341 + 'A','r','d','u','i','n','o',' ','L','L','C' +#elif USB_VID == 0x1b4f + 'S','p','a','r','k','F','u','n',' ',' ',' ' +#else + 'U','n','k','n','o','w','n',' ',' ',' ',' ' +#endif +}; + +#ifdef CDC_ENABLED +#define DEVICE_CLASS 0x02 +#else +#define DEVICE_CLASS 0x00 +#endif + +// DEVICE DESCRIPTOR +const DeviceDescriptor USB_DeviceDescriptor = + D_DEVICE(0x00,0x00,0x00,64,USB_VID,USB_PID,0x100,IMANUFACTURER,IPRODUCT,0,1); + +const DeviceDescriptor USB_DeviceDescriptorA = + D_DEVICE(DEVICE_CLASS,0x00,0x00,64,USB_VID,USB_PID,0x100,IMANUFACTURER,IPRODUCT,0,1); + +//================================================================== +//================================================================== + +volatile u8 _usbConfiguration = 0; + +static inline void WaitIN(void) +{ + while (!(UEINTX & (1< len) + n = len; + len -= n; + { + LockEP lock(ep); + if (ep & TRANSFER_ZERO) + { + while (n--) + Send8(0); + } + else if (ep & TRANSFER_PGM) + { + while (n--) + Send8(pgm_read_byte(data++)); + } + else + { + while (n--) + Send8(*data++); + } + if (!ReadWriteAllowed() || ((len == 0) && (ep & TRANSFER_RELEASE))) // Release full buffer + ReleaseTX(); + } + } + TXLED1; // light the TX LED + TxLEDPulse = TX_RX_LED_PULSE_MS; + return r; +} + +extern const u8 _initEndpoints[] PROGMEM; +const u8 _initEndpoints[] = +{ + 0, + +#ifdef CDC_ENABLED + EP_TYPE_INTERRUPT_IN, // CDC_ENDPOINT_ACM + EP_TYPE_BULK_OUT, // CDC_ENDPOINT_OUT + EP_TYPE_BULK_IN, // CDC_ENDPOINT_IN +#endif + +#ifdef HID_ENABLED + EP_TYPE_INTERRUPT_IN // HID_ENDPOINT_INT +#endif +}; + +#define EP_SINGLE_64 0x32 // EP0 +#define EP_DOUBLE_64 0x36 // Other endpoints + +static +void InitEP(u8 index, u8 type, u8 size) +{ + UENUM = index; + UECONX = 1; + UECFG0X = type; + UECFG1X = size; +} + +static +void InitEndpoints() +{ + for (u8 i = 1; i < sizeof(_initEndpoints); i++) + { + UENUM = i; + UECONX = 1; + UECFG0X = pgm_read_byte(_initEndpoints+i); + UECFG1X = EP_DOUBLE_64; + } + UERST = 0x7E; // And reset them + UERST = 0; +} + +// Handle CLASS_INTERFACE requests +static +bool ClassInterfaceRequest(Setup& setup) +{ + u8 i = setup.wIndex; + +#ifdef CDC_ENABLED + if (CDC_ACM_INTERFACE == i) + return CDC_Setup(setup); +#endif + +#ifdef HID_ENABLED + if (HID_INTERFACE == i) + return HID_Setup(setup); +#endif + return false; +} + +int _cmark; +int _cend; +void InitControl(int end) +{ + SetEP(0); + _cmark = 0; + _cend = end; +} + +static +bool SendControl(u8 d) +{ + if (_cmark < _cend) + { + if (!WaitForINOrOUT()) + return false; + Send8(d); + if (!((_cmark + 1) & 0x3F)) + ClearIN(); // Fifo is full, release this packet + } + _cmark++; + return true; +}; + +// Clipped by _cmark/_cend +int USB_SendControl(u8 flags, const void* d, int len) +{ + int sent = len; + const u8* data = (const u8*)d; + bool pgm = flags & TRANSFER_PGM; + while (len--) + { + u8 c = pgm ? pgm_read_byte(data++) : *data++; + if (!SendControl(c)) + return -1; + } + return sent; +} + +// Does not timeout or cross fifo boundaries +// Will only work for transfers <= 64 bytes +// TODO +int USB_RecvControl(void* d, int len) +{ + WaitOUT(); + Recv((u8*)d,len); + ClearOUT(); + return len; +} + +int SendInterfaces() +{ + int total = 0; + u8 interfaces = 0; + +#ifdef CDC_ENABLED + total = CDC_GetInterface(&interfaces); +#endif + +#ifdef HID_ENABLED + total += HID_GetInterface(&interfaces); +#endif + + return interfaces; +} + +// Construct a dynamic configuration descriptor +// This really needs dynamic endpoint allocation etc +// TODO +static +bool SendConfiguration(int maxlen) +{ + // Count and measure interfaces + InitControl(0); + int interfaces = SendInterfaces(); + ConfigDescriptor config = D_CONFIG(_cmark + sizeof(ConfigDescriptor),interfaces); + + // Now send them + InitControl(maxlen); + USB_SendControl(0,&config,sizeof(ConfigDescriptor)); + SendInterfaces(); + return true; +} + +u8 _cdcComposite = 0; + +static +bool SendDescriptor(Setup& setup) +{ + u8 t = setup.wValueH; + if (USB_CONFIGURATION_DESCRIPTOR_TYPE == t) + return SendConfiguration(setup.wLength); + + InitControl(setup.wLength); +#ifdef HID_ENABLED + if (HID_REPORT_DESCRIPTOR_TYPE == t) + return HID_GetDescriptor(t); +#endif + + u8 desc_length = 0; + const u8* desc_addr = 0; + if (USB_DEVICE_DESCRIPTOR_TYPE == t) + { + if (setup.wLength == 8) + _cdcComposite = 1; + desc_addr = _cdcComposite ? (const u8*)&USB_DeviceDescriptorA : (const u8*)&USB_DeviceDescriptor; + } + else if (USB_STRING_DESCRIPTOR_TYPE == t) + { + if (setup.wValueL == 0) + desc_addr = (const u8*)&STRING_LANGUAGE; + else if (setup.wValueL == IPRODUCT) + desc_addr = (const u8*)&STRING_IPRODUCT; + else if (setup.wValueL == IMANUFACTURER) + desc_addr = (const u8*)&STRING_IMANUFACTURER; + else + return false; + } + + if (desc_addr == 0) + return false; + if (desc_length == 0) + desc_length = pgm_read_byte(desc_addr); + + USB_SendControl(TRANSFER_PGM,desc_addr,desc_length); + return true; +} + +// Endpoint 0 interrupt +ISR(USB_COM_vect) +{ + SetEP(0); + if (!ReceivedSetupInt()) + return; + + Setup setup; + Recv((u8*)&setup,8); + ClearSetupInt(); + + u8 requestType = setup.bmRequestType; + if (requestType & REQUEST_DEVICETOHOST) + WaitIN(); + else + ClearIN(); + + bool ok = true; + if (REQUEST_STANDARD == (requestType & REQUEST_TYPE)) + { + // Standard Requests + u8 r = setup.bRequest; + if (GET_STATUS == r) + { + Send8(0); // TODO + Send8(0); + } + else if (CLEAR_FEATURE == r) + { + } + else if (SET_FEATURE == r) + { + } + else if (SET_ADDRESS == r) + { + WaitIN(); + UDADDR = setup.wValueL | (1<> 8) & 0xFF) + +#define CDC_V1_10 0x0110 +#define CDC_COMMUNICATION_INTERFACE_CLASS 0x02 + +#define CDC_CALL_MANAGEMENT 0x01 +#define CDC_ABSTRACT_CONTROL_MODEL 0x02 +#define CDC_HEADER 0x00 +#define CDC_ABSTRACT_CONTROL_MANAGEMENT 0x02 +#define CDC_UNION 0x06 +#define CDC_CS_INTERFACE 0x24 +#define CDC_CS_ENDPOINT 0x25 +#define CDC_DATA_INTERFACE_CLASS 0x0A + +#define MSC_SUBCLASS_SCSI 0x06 +#define MSC_PROTOCOL_BULK_ONLY 0x50 + +#define HID_HID_DESCRIPTOR_TYPE 0x21 +#define HID_REPORT_DESCRIPTOR_TYPE 0x22 +#define HID_PHYSICAL_DESCRIPTOR_TYPE 0x23 + + +// Device +typedef struct { + u8 len; // 18 + u8 dtype; // 1 USB_DEVICE_DESCRIPTOR_TYPE + u16 usbVersion; // 0x200 + u8 deviceClass; + u8 deviceSubClass; + u8 deviceProtocol; + u8 packetSize0; // Packet 0 + u16 idVendor; + u16 idProduct; + u16 deviceVersion; // 0x100 + u8 iManufacturer; + u8 iProduct; + u8 iSerialNumber; + u8 bNumConfigurations; +} DeviceDescriptor; + +// Config +typedef struct { + u8 len; // 9 + u8 dtype; // 2 + u16 clen; // total length + u8 numInterfaces; + u8 config; + u8 iconfig; + u8 attributes; + u8 maxPower; +} ConfigDescriptor; + +// String + +// Interface +typedef struct +{ + u8 len; // 9 + u8 dtype; // 4 + u8 number; + u8 alternate; + u8 numEndpoints; + u8 interfaceClass; + u8 interfaceSubClass; + u8 protocol; + u8 iInterface; +} InterfaceDescriptor; + +// Endpoint +typedef struct +{ + u8 len; // 7 + u8 dtype; // 5 + u8 addr; + u8 attr; + u16 packetSize; + u8 interval; +} EndpointDescriptor; + +// Interface Association Descriptor +// Used to bind 2 interfaces together in CDC compostite device +typedef struct +{ + u8 len; // 8 + u8 dtype; // 11 + u8 firstInterface; + u8 interfaceCount; + u8 functionClass; + u8 funtionSubClass; + u8 functionProtocol; + u8 iInterface; +} IADDescriptor; + +// CDC CS interface descriptor +typedef struct +{ + u8 len; // 5 + u8 dtype; // 0x24 + u8 subtype; + u8 d0; + u8 d1; +} CDCCSInterfaceDescriptor; + +typedef struct +{ + u8 len; // 4 + u8 dtype; // 0x24 + u8 subtype; + u8 d0; +} CDCCSInterfaceDescriptor4; + +typedef struct +{ + u8 len; + u8 dtype; // 0x24 + u8 subtype; // 1 + u8 bmCapabilities; + u8 bDataInterface; +} CMFunctionalDescriptor; + +typedef struct +{ + u8 len; + u8 dtype; // 0x24 + u8 subtype; // 1 + u8 bmCapabilities; +} ACMFunctionalDescriptor; + +typedef struct +{ + // IAD + IADDescriptor iad; // Only needed on compound device + + // Control + InterfaceDescriptor cif; // + CDCCSInterfaceDescriptor header; + CMFunctionalDescriptor callManagement; // Call Management + ACMFunctionalDescriptor controlManagement; // ACM + CDCCSInterfaceDescriptor functionalDescriptor; // CDC_UNION + EndpointDescriptor cifin; + + // Data + InterfaceDescriptor dif; + EndpointDescriptor in; + EndpointDescriptor out; +} CDCDescriptor; + +typedef struct +{ + InterfaceDescriptor msc; + EndpointDescriptor in; + EndpointDescriptor out; +} MSCDescriptor; + +typedef struct +{ + u8 len; // 9 + u8 dtype; // 0x21 + u8 addr; + u8 versionL; // 0x101 + u8 versionH; // 0x101 + u8 country; + u8 desctype; // 0x22 report + u8 descLenL; + u8 descLenH; +} HIDDescDescriptor; + +typedef struct +{ + InterfaceDescriptor hid; + HIDDescDescriptor desc; + EndpointDescriptor in; +} HIDDescriptor; + + +#define D_DEVICE(_class,_subClass,_proto,_packetSize0,_vid,_pid,_version,_im,_ip,_is,_configs) \ + { 18, 1, 0x200, _class,_subClass,_proto,_packetSize0,_vid,_pid,_version,_im,_ip,_is,_configs } + +#define D_CONFIG(_totalLength,_interfaces) \ + { 9, 2, _totalLength,_interfaces, 1, 0, USB_CONFIG_BUS_POWERED, USB_CONFIG_POWER_MA(500) } + +#define D_INTERFACE(_n,_numEndpoints,_class,_subClass,_protocol) \ + { 9, 4, _n, 0, _numEndpoints, _class,_subClass, _protocol, 0 } + +#define D_ENDPOINT(_addr,_attr,_packetSize, _interval) \ + { 7, 5, _addr,_attr,_packetSize, _interval } + +#define D_IAD(_firstInterface, _count, _class, _subClass, _protocol) \ + { 8, 11, _firstInterface, _count, _class, _subClass, _protocol, 0 } + +#define D_HIDREPORT(_descriptorLength) \ + { 9, 0x21, 0x1, 0x1, 0, 1, 0x22, _descriptorLength, 0 } + +#define D_CDCCS(_subtype,_d0,_d1) { 5, 0x24, _subtype, _d0, _d1 } +#define D_CDCCS4(_subtype,_d0) { 4, 0x24, _subtype, _d0 } + + +#endif \ No newline at end of file diff --git a/hardware/arduino/cores/robot/USBDesc.h b/hardware/arduino/cores/robot/USBDesc.h new file mode 100644 index 00000000000..900713e0f92 --- /dev/null +++ b/hardware/arduino/cores/robot/USBDesc.h @@ -0,0 +1,63 @@ + + +/* Copyright (c) 2011, Peter Barrett +** +** Permission to use, copy, modify, and/or distribute this software for +** any purpose with or without fee is hereby granted, provided that the +** above copyright notice and this permission notice appear in all copies. +** +** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL +** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED +** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR +** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES +** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS +** SOFTWARE. +*/ + +#define CDC_ENABLED +#define HID_ENABLED + + +#ifdef CDC_ENABLED +#define CDC_INTERFACE_COUNT 2 +#define CDC_ENPOINT_COUNT 3 +#else +#define CDC_INTERFACE_COUNT 0 +#define CDC_ENPOINT_COUNT 0 +#endif + +#ifdef HID_ENABLED +#define HID_INTERFACE_COUNT 1 +#define HID_ENPOINT_COUNT 1 +#else +#define HID_INTERFACE_COUNT 0 +#define HID_ENPOINT_COUNT 0 +#endif + +#define CDC_ACM_INTERFACE 0 // CDC ACM +#define CDC_DATA_INTERFACE 1 // CDC Data +#define CDC_FIRST_ENDPOINT 1 +#define CDC_ENDPOINT_ACM (CDC_FIRST_ENDPOINT) // CDC First +#define CDC_ENDPOINT_OUT (CDC_FIRST_ENDPOINT+1) +#define CDC_ENDPOINT_IN (CDC_FIRST_ENDPOINT+2) + +#define HID_INTERFACE (CDC_ACM_INTERFACE + CDC_INTERFACE_COUNT) // HID Interface +#define HID_FIRST_ENDPOINT (CDC_FIRST_ENDPOINT + CDC_ENPOINT_COUNT) +#define HID_ENDPOINT_INT (HID_FIRST_ENDPOINT) + +#define INTERFACE_COUNT (MSC_INTERFACE + MSC_INTERFACE_COUNT) + +#ifdef CDC_ENABLED +#define CDC_RX CDC_ENDPOINT_OUT +#define CDC_TX CDC_ENDPOINT_IN +#endif + +#ifdef HID_ENABLED +#define HID_TX HID_ENDPOINT_INT +#endif + +#define IMANUFACTURER 1 +#define IPRODUCT 2 + diff --git a/hardware/arduino/cores/robot/Udp.h b/hardware/arduino/cores/robot/Udp.h new file mode 100644 index 00000000000..dc5644b9df2 --- /dev/null +++ b/hardware/arduino/cores/robot/Udp.h @@ -0,0 +1,88 @@ +/* + * Udp.cpp: Library to send/receive UDP packets. + * + * NOTE: UDP is fast, but has some important limitations (thanks to Warren Gray for mentioning these) + * 1) UDP does not guarantee the order in which assembled UDP packets are received. This + * might not happen often in practice, but in larger network topologies, a UDP + * packet can be received out of sequence. + * 2) UDP does not guard against lost packets - so packets *can* disappear without the sender being + * aware of it. Again, this may not be a concern in practice on small local networks. + * For more information, see http://www.cafeaulait.org/course/week12/35.html + * + * MIT License: + * Copyright (c) 2008 Bjoern Hartmann + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * bjoern@cs.stanford.edu 12/30/2008 + */ + +#ifndef udp_h +#define udp_h + +#include +#include + +class UDP : public Stream { + +public: + virtual uint8_t begin(uint16_t) =0; // initialize, start listening on specified port. Returns 1 if successful, 0 if there are no sockets available to use + virtual void stop() =0; // Finish with the UDP socket + + // Sending UDP packets + + // Start building up a packet to send to the remote host specific in ip and port + // Returns 1 if successful, 0 if there was a problem with the supplied IP address or port + virtual int beginPacket(IPAddress ip, uint16_t port) =0; + // Start building up a packet to send to the remote host specific in host and port + // Returns 1 if successful, 0 if there was a problem resolving the hostname or port + virtual int beginPacket(const char *host, uint16_t port) =0; + // Finish off this packet and send it + // Returns 1 if the packet was sent successfully, 0 if there was an error + virtual int endPacket() =0; + // Write a single byte into the packet + virtual size_t write(uint8_t) =0; + // Write size bytes from buffer into the packet + virtual size_t write(const uint8_t *buffer, size_t size) =0; + + // Start processing the next available incoming packet + // Returns the size of the packet in bytes, or 0 if no packets are available + virtual int parsePacket() =0; + // Number of bytes remaining in the current packet + virtual int available() =0; + // Read a single byte from the current packet + virtual int read() =0; + // Read up to len bytes from the current packet and place them into buffer + // Returns the number of bytes read, or 0 if none are available + virtual int read(unsigned char* buffer, size_t len) =0; + // Read up to len characters from the current packet and place them into buffer + // Returns the number of characters read, or 0 if none are available + virtual int read(char* buffer, size_t len) =0; + // Return the next byte from the current packet without moving on to the next byte + virtual int peek() =0; + virtual void flush() =0; // Finish reading the current packet + + // Return the IP address of the host who sent the current incoming packet + virtual IPAddress remoteIP() =0; + // Return the port of the host who sent the current incoming packet + virtual uint16_t remotePort() =0; +protected: + uint8_t* rawIPAddress(IPAddress& addr) { return addr.raw_address(); }; +}; + +#endif diff --git a/hardware/arduino/cores/robot/WCharacter.h b/hardware/arduino/cores/robot/WCharacter.h new file mode 100644 index 00000000000..79733b50a53 --- /dev/null +++ b/hardware/arduino/cores/robot/WCharacter.h @@ -0,0 +1,168 @@ +/* + WCharacter.h - Character utility functions for Wiring & Arduino + Copyright (c) 2010 Hernando Barragan. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef Character_h +#define Character_h + +#include + +// WCharacter.h prototypes +inline boolean isAlphaNumeric(int c) __attribute__((always_inline)); +inline boolean isAlpha(int c) __attribute__((always_inline)); +inline boolean isAscii(int c) __attribute__((always_inline)); +inline boolean isWhitespace(int c) __attribute__((always_inline)); +inline boolean isControl(int c) __attribute__((always_inline)); +inline boolean isDigit(int c) __attribute__((always_inline)); +inline boolean isGraph(int c) __attribute__((always_inline)); +inline boolean isLowerCase(int c) __attribute__((always_inline)); +inline boolean isPrintable(int c) __attribute__((always_inline)); +inline boolean isPunct(int c) __attribute__((always_inline)); +inline boolean isSpace(int c) __attribute__((always_inline)); +inline boolean isUpperCase(int c) __attribute__((always_inline)); +inline boolean isHexadecimalDigit(int c) __attribute__((always_inline)); +inline int toAscii(int c) __attribute__((always_inline)); +inline int toLowerCase(int c) __attribute__((always_inline)); +inline int toUpperCase(int c)__attribute__((always_inline)); + + +// Checks for an alphanumeric character. +// It is equivalent to (isalpha(c) || isdigit(c)). +inline boolean isAlphaNumeric(int c) +{ + return ( isalnum(c) == 0 ? false : true); +} + + +// Checks for an alphabetic character. +// It is equivalent to (isupper(c) || islower(c)). +inline boolean isAlpha(int c) +{ + return ( isalpha(c) == 0 ? false : true); +} + + +// Checks whether c is a 7-bit unsigned char value +// that fits into the ASCII character set. +inline boolean isAscii(int c) +{ + return ( isascii (c) == 0 ? false : true); +} + + +// Checks for a blank character, that is, a space or a tab. +inline boolean isWhitespace(int c) +{ + return ( isblank (c) == 0 ? false : true); +} + + +// Checks for a control character. +inline boolean isControl(int c) +{ + return ( iscntrl (c) == 0 ? false : true); +} + + +// Checks for a digit (0 through 9). +inline boolean isDigit(int c) +{ + return ( isdigit (c) == 0 ? false : true); +} + + +// Checks for any printable character except space. +inline boolean isGraph(int c) +{ + return ( isgraph (c) == 0 ? false : true); +} + + +// Checks for a lower-case character. +inline boolean isLowerCase(int c) +{ + return (islower (c) == 0 ? false : true); +} + + +// Checks for any printable character including space. +inline boolean isPrintable(int c) +{ + return ( isprint (c) == 0 ? false : true); +} + + +// Checks for any printable character which is not a space +// or an alphanumeric character. +inline boolean isPunct(int c) +{ + return ( ispunct (c) == 0 ? false : true); +} + + +// Checks for white-space characters. For the avr-libc library, +// these are: space, formfeed ('\f'), newline ('\n'), carriage +// return ('\r'), horizontal tab ('\t'), and vertical tab ('\v'). +inline boolean isSpace(int c) +{ + return ( isspace (c) == 0 ? false : true); +} + + +// Checks for an uppercase letter. +inline boolean isUpperCase(int c) +{ + return ( isupper (c) == 0 ? false : true); +} + + +// Checks for a hexadecimal digits, i.e. one of 0 1 2 3 4 5 6 7 +// 8 9 a b c d e f A B C D E F. +inline boolean isHexadecimalDigit(int c) +{ + return ( isxdigit (c) == 0 ? false : true); +} + + +// Converts c to a 7-bit unsigned char value that fits into the +// ASCII character set, by clearing the high-order bits. +inline int toAscii(int c) +{ + return toascii (c); +} + + +// Warning: +// Many people will be unhappy if you use this function. +// This function will convert accented letters into random +// characters. + +// Converts the letter c to lower case, if possible. +inline int toLowerCase(int c) +{ + return tolower (c); +} + + +// Converts the letter c to upper case, if possible. +inline int toUpperCase(int c) +{ + return toupper (c); +} + +#endif \ No newline at end of file diff --git a/hardware/arduino/cores/robot/WInterrupts.c b/hardware/arduino/cores/robot/WInterrupts.c new file mode 100644 index 00000000000..d3fbf100e3e --- /dev/null +++ b/hardware/arduino/cores/robot/WInterrupts.c @@ -0,0 +1,334 @@ +/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */ + +/* + Part of the Wiring project - http://wiring.uniandes.edu.co + + Copyright (c) 2004-05 Hernando Barragan + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA + + Modified 24 November 2006 by David A. Mellis + Modified 1 August 2010 by Mark Sproul +*/ + +#include +#include +#include +#include +#include + +#include "wiring_private.h" + +static volatile voidFuncPtr intFunc[EXTERNAL_NUM_INTERRUPTS]; +// volatile static voidFuncPtr twiIntFunc; + +void attachInterrupt(uint8_t interruptNum, void (*userFunc)(void), int mode) { + if(interruptNum < EXTERNAL_NUM_INTERRUPTS) { + intFunc[interruptNum] = userFunc; + + // Configure the interrupt mode (trigger on low input, any change, rising + // edge, or falling edge). The mode constants were chosen to correspond + // to the configuration bits in the hardware register, so we simply shift + // the mode into place. + + // Enable the interrupt. + + switch (interruptNum) { +#if defined(__AVR_ATmega32U4__) + // I hate doing this, but the register assignment differs between the 1280/2560 + // and the 32U4. Since avrlib defines registers PCMSK1 and PCMSK2 that aren't + // even present on the 32U4 this is the only way to distinguish between them. + case 0: + EICRA = (EICRA & ~((1<= howbig) { + return howsmall; + } + long diff = howbig - howsmall; + return random(diff) + howsmall; +} + +long map(long x, long in_min, long in_max, long out_min, long out_max) +{ + return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; +} + +unsigned int makeWord(unsigned int w) { return w; } +unsigned int makeWord(unsigned char h, unsigned char l) { return (h << 8) | l; } \ No newline at end of file diff --git a/hardware/arduino/cores/robot/WString.cpp b/hardware/arduino/cores/robot/WString.cpp new file mode 100644 index 00000000000..c6839fc0d92 --- /dev/null +++ b/hardware/arduino/cores/robot/WString.cpp @@ -0,0 +1,645 @@ +/* + WString.cpp - String library for Wiring & Arduino + ...mostly rewritten by Paul Stoffregen... + Copyright (c) 2009-10 Hernando Barragan. All rights reserved. + Copyright 2011, Paul Stoffregen, paul@pjrc.com + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "WString.h" + + +/*********************************************/ +/* Constructors */ +/*********************************************/ + +String::String(const char *cstr) +{ + init(); + if (cstr) copy(cstr, strlen(cstr)); +} + +String::String(const String &value) +{ + init(); + *this = value; +} + +#ifdef __GXX_EXPERIMENTAL_CXX0X__ +String::String(String &&rval) +{ + init(); + move(rval); +} +String::String(StringSumHelper &&rval) +{ + init(); + move(rval); +} +#endif + +String::String(char c) +{ + init(); + char buf[2]; + buf[0] = c; + buf[1] = 0; + *this = buf; +} + +String::String(unsigned char value, unsigned char base) +{ + init(); + char buf[9]; + utoa(value, buf, base); + *this = buf; +} + +String::String(int value, unsigned char base) +{ + init(); + char buf[18]; + itoa(value, buf, base); + *this = buf; +} + +String::String(unsigned int value, unsigned char base) +{ + init(); + char buf[17]; + utoa(value, buf, base); + *this = buf; +} + +String::String(long value, unsigned char base) +{ + init(); + char buf[34]; + ltoa(value, buf, base); + *this = buf; +} + +String::String(unsigned long value, unsigned char base) +{ + init(); + char buf[33]; + ultoa(value, buf, base); + *this = buf; +} + +String::~String() +{ + free(buffer); +} + +/*********************************************/ +/* Memory Management */ +/*********************************************/ + +inline void String::init(void) +{ + buffer = NULL; + capacity = 0; + len = 0; + flags = 0; +} + +void String::invalidate(void) +{ + if (buffer) free(buffer); + buffer = NULL; + capacity = len = 0; +} + +unsigned char String::reserve(unsigned int size) +{ + if (buffer && capacity >= size) return 1; + if (changeBuffer(size)) { + if (len == 0) buffer[0] = 0; + return 1; + } + return 0; +} + +unsigned char String::changeBuffer(unsigned int maxStrLen) +{ + char *newbuffer = (char *)realloc(buffer, maxStrLen + 1); + if (newbuffer) { + buffer = newbuffer; + capacity = maxStrLen; + return 1; + } + return 0; +} + +/*********************************************/ +/* Copy and Move */ +/*********************************************/ + +String & String::copy(const char *cstr, unsigned int length) +{ + if (!reserve(length)) { + invalidate(); + return *this; + } + len = length; + strcpy(buffer, cstr); + return *this; +} + +#ifdef __GXX_EXPERIMENTAL_CXX0X__ +void String::move(String &rhs) +{ + if (buffer) { + if (capacity >= rhs.len) { + strcpy(buffer, rhs.buffer); + len = rhs.len; + rhs.len = 0; + return; + } else { + free(buffer); + } + } + buffer = rhs.buffer; + capacity = rhs.capacity; + len = rhs.len; + rhs.buffer = NULL; + rhs.capacity = 0; + rhs.len = 0; +} +#endif + +String & String::operator = (const String &rhs) +{ + if (this == &rhs) return *this; + + if (rhs.buffer) copy(rhs.buffer, rhs.len); + else invalidate(); + + return *this; +} + +#ifdef __GXX_EXPERIMENTAL_CXX0X__ +String & String::operator = (String &&rval) +{ + if (this != &rval) move(rval); + return *this; +} + +String & String::operator = (StringSumHelper &&rval) +{ + if (this != &rval) move(rval); + return *this; +} +#endif + +String & String::operator = (const char *cstr) +{ + if (cstr) copy(cstr, strlen(cstr)); + else invalidate(); + + return *this; +} + +/*********************************************/ +/* concat */ +/*********************************************/ + +unsigned char String::concat(const String &s) +{ + return concat(s.buffer, s.len); +} + +unsigned char String::concat(const char *cstr, unsigned int length) +{ + unsigned int newlen = len + length; + if (!cstr) return 0; + if (length == 0) return 1; + if (!reserve(newlen)) return 0; + strcpy(buffer + len, cstr); + len = newlen; + return 1; +} + +unsigned char String::concat(const char *cstr) +{ + if (!cstr) return 0; + return concat(cstr, strlen(cstr)); +} + +unsigned char String::concat(char c) +{ + char buf[2]; + buf[0] = c; + buf[1] = 0; + return concat(buf, 1); +} + +unsigned char String::concat(unsigned char num) +{ + char buf[4]; + itoa(num, buf, 10); + return concat(buf, strlen(buf)); +} + +unsigned char String::concat(int num) +{ + char buf[7]; + itoa(num, buf, 10); + return concat(buf, strlen(buf)); +} + +unsigned char String::concat(unsigned int num) +{ + char buf[6]; + utoa(num, buf, 10); + return concat(buf, strlen(buf)); +} + +unsigned char String::concat(long num) +{ + char buf[12]; + ltoa(num, buf, 10); + return concat(buf, strlen(buf)); +} + +unsigned char String::concat(unsigned long num) +{ + char buf[11]; + ultoa(num, buf, 10); + return concat(buf, strlen(buf)); +} + +/*********************************************/ +/* Concatenate */ +/*********************************************/ + +StringSumHelper & operator + (const StringSumHelper &lhs, const String &rhs) +{ + StringSumHelper &a = const_cast(lhs); + if (!a.concat(rhs.buffer, rhs.len)) a.invalidate(); + return a; +} + +StringSumHelper & operator + (const StringSumHelper &lhs, const char *cstr) +{ + StringSumHelper &a = const_cast(lhs); + if (!cstr || !a.concat(cstr, strlen(cstr))) a.invalidate(); + return a; +} + +StringSumHelper & operator + (const StringSumHelper &lhs, char c) +{ + StringSumHelper &a = const_cast(lhs); + if (!a.concat(c)) a.invalidate(); + return a; +} + +StringSumHelper & operator + (const StringSumHelper &lhs, unsigned char num) +{ + StringSumHelper &a = const_cast(lhs); + if (!a.concat(num)) a.invalidate(); + return a; +} + +StringSumHelper & operator + (const StringSumHelper &lhs, int num) +{ + StringSumHelper &a = const_cast(lhs); + if (!a.concat(num)) a.invalidate(); + return a; +} + +StringSumHelper & operator + (const StringSumHelper &lhs, unsigned int num) +{ + StringSumHelper &a = const_cast(lhs); + if (!a.concat(num)) a.invalidate(); + return a; +} + +StringSumHelper & operator + (const StringSumHelper &lhs, long num) +{ + StringSumHelper &a = const_cast(lhs); + if (!a.concat(num)) a.invalidate(); + return a; +} + +StringSumHelper & operator + (const StringSumHelper &lhs, unsigned long num) +{ + StringSumHelper &a = const_cast(lhs); + if (!a.concat(num)) a.invalidate(); + return a; +} + +/*********************************************/ +/* Comparison */ +/*********************************************/ + +int String::compareTo(const String &s) const +{ + if (!buffer || !s.buffer) { + if (s.buffer && s.len > 0) return 0 - *(unsigned char *)s.buffer; + if (buffer && len > 0) return *(unsigned char *)buffer; + return 0; + } + return strcmp(buffer, s.buffer); +} + +unsigned char String::equals(const String &s2) const +{ + return (len == s2.len && compareTo(s2) == 0); +} + +unsigned char String::equals(const char *cstr) const +{ + if (len == 0) return (cstr == NULL || *cstr == 0); + if (cstr == NULL) return buffer[0] == 0; + return strcmp(buffer, cstr) == 0; +} + +unsigned char String::operator<(const String &rhs) const +{ + return compareTo(rhs) < 0; +} + +unsigned char String::operator>(const String &rhs) const +{ + return compareTo(rhs) > 0; +} + +unsigned char String::operator<=(const String &rhs) const +{ + return compareTo(rhs) <= 0; +} + +unsigned char String::operator>=(const String &rhs) const +{ + return compareTo(rhs) >= 0; +} + +unsigned char String::equalsIgnoreCase( const String &s2 ) const +{ + if (this == &s2) return 1; + if (len != s2.len) return 0; + if (len == 0) return 1; + const char *p1 = buffer; + const char *p2 = s2.buffer; + while (*p1) { + if (tolower(*p1++) != tolower(*p2++)) return 0; + } + return 1; +} + +unsigned char String::startsWith( const String &s2 ) const +{ + if (len < s2.len) return 0; + return startsWith(s2, 0); +} + +unsigned char String::startsWith( const String &s2, unsigned int offset ) const +{ + if (offset > len - s2.len || !buffer || !s2.buffer) return 0; + return strncmp( &buffer[offset], s2.buffer, s2.len ) == 0; +} + +unsigned char String::endsWith( const String &s2 ) const +{ + if ( len < s2.len || !buffer || !s2.buffer) return 0; + return strcmp(&buffer[len - s2.len], s2.buffer) == 0; +} + +/*********************************************/ +/* Character Access */ +/*********************************************/ + +char String::charAt(unsigned int loc) const +{ + return operator[](loc); +} + +void String::setCharAt(unsigned int loc, char c) +{ + if (loc < len) buffer[loc] = c; +} + +char & String::operator[](unsigned int index) +{ + static char dummy_writable_char; + if (index >= len || !buffer) { + dummy_writable_char = 0; + return dummy_writable_char; + } + return buffer[index]; +} + +char String::operator[]( unsigned int index ) const +{ + if (index >= len || !buffer) return 0; + return buffer[index]; +} + +void String::getBytes(unsigned char *buf, unsigned int bufsize, unsigned int index) const +{ + if (!bufsize || !buf) return; + if (index >= len) { + buf[0] = 0; + return; + } + unsigned int n = bufsize - 1; + if (n > len - index) n = len - index; + strncpy((char *)buf, buffer + index, n); + buf[n] = 0; +} + +/*********************************************/ +/* Search */ +/*********************************************/ + +int String::indexOf(char c) const +{ + return indexOf(c, 0); +} + +int String::indexOf( char ch, unsigned int fromIndex ) const +{ + if (fromIndex >= len) return -1; + const char* temp = strchr(buffer + fromIndex, ch); + if (temp == NULL) return -1; + return temp - buffer; +} + +int String::indexOf(const String &s2) const +{ + return indexOf(s2, 0); +} + +int String::indexOf(const String &s2, unsigned int fromIndex) const +{ + if (fromIndex >= len) return -1; + const char *found = strstr(buffer + fromIndex, s2.buffer); + if (found == NULL) return -1; + return found - buffer; +} + +int String::lastIndexOf( char theChar ) const +{ + return lastIndexOf(theChar, len - 1); +} + +int String::lastIndexOf(char ch, unsigned int fromIndex) const +{ + if (fromIndex >= len) return -1; + char tempchar = buffer[fromIndex + 1]; + buffer[fromIndex + 1] = '\0'; + char* temp = strrchr( buffer, ch ); + buffer[fromIndex + 1] = tempchar; + if (temp == NULL) return -1; + return temp - buffer; +} + +int String::lastIndexOf(const String &s2) const +{ + return lastIndexOf(s2, len - s2.len); +} + +int String::lastIndexOf(const String &s2, unsigned int fromIndex) const +{ + if (s2.len == 0 || len == 0 || s2.len > len) return -1; + if (fromIndex >= len) fromIndex = len - 1; + int found = -1; + for (char *p = buffer; p <= buffer + fromIndex; p++) { + p = strstr(p, s2.buffer); + if (!p) break; + if ((unsigned int)(p - buffer) <= fromIndex) found = p - buffer; + } + return found; +} + +String String::substring( unsigned int left ) const +{ + return substring(left, len); +} + +String String::substring(unsigned int left, unsigned int right) const +{ + if (left > right) { + unsigned int temp = right; + right = left; + left = temp; + } + String out; + if (left > len) return out; + if (right > len) right = len; + char temp = buffer[right]; // save the replaced character + buffer[right] = '\0'; + out = buffer + left; // pointer arithmetic + buffer[right] = temp; //restore character + return out; +} + +/*********************************************/ +/* Modification */ +/*********************************************/ + +void String::replace(char find, char replace) +{ + if (!buffer) return; + for (char *p = buffer; *p; p++) { + if (*p == find) *p = replace; + } +} + +void String::replace(const String& find, const String& replace) +{ + if (len == 0 || find.len == 0) return; + int diff = replace.len - find.len; + char *readFrom = buffer; + char *foundAt; + if (diff == 0) { + while ((foundAt = strstr(readFrom, find.buffer)) != NULL) { + memcpy(foundAt, replace.buffer, replace.len); + readFrom = foundAt + replace.len; + } + } else if (diff < 0) { + char *writeTo = buffer; + while ((foundAt = strstr(readFrom, find.buffer)) != NULL) { + unsigned int n = foundAt - readFrom; + memcpy(writeTo, readFrom, n); + writeTo += n; + memcpy(writeTo, replace.buffer, replace.len); + writeTo += replace.len; + readFrom = foundAt + find.len; + len += diff; + } + strcpy(writeTo, readFrom); + } else { + unsigned int size = len; // compute size needed for result + while ((foundAt = strstr(readFrom, find.buffer)) != NULL) { + readFrom = foundAt + find.len; + size += diff; + } + if (size == len) return; + if (size > capacity && !changeBuffer(size)) return; // XXX: tell user! + int index = len - 1; + while (index >= 0 && (index = lastIndexOf(find, index)) >= 0) { + readFrom = buffer + index + find.len; + memmove(readFrom + diff, readFrom, len - (readFrom - buffer)); + len += diff; + buffer[len] = 0; + memcpy(buffer + index, replace.buffer, replace.len); + index--; + } + } +} + +void String::toLowerCase(void) +{ + if (!buffer) return; + for (char *p = buffer; *p; p++) { + *p = tolower(*p); + } +} + +void String::toUpperCase(void) +{ + if (!buffer) return; + for (char *p = buffer; *p; p++) { + *p = toupper(*p); + } +} + +void String::trim(void) +{ + if (!buffer || len == 0) return; + char *begin = buffer; + while (isspace(*begin)) begin++; + char *end = buffer + len - 1; + while (isspace(*end) && end >= begin) end--; + len = end + 1 - begin; + if (begin > buffer) memcpy(buffer, begin, len); + buffer[len] = 0; +} + +/*********************************************/ +/* Parsing / Conversion */ +/*********************************************/ + +long String::toInt(void) const +{ + if (buffer) return atol(buffer); + return 0; +} + + diff --git a/hardware/arduino/cores/robot/WString.h b/hardware/arduino/cores/robot/WString.h new file mode 100644 index 00000000000..642b016c53c --- /dev/null +++ b/hardware/arduino/cores/robot/WString.h @@ -0,0 +1,206 @@ +/* + WString.h - String library for Wiring & Arduino + ...mostly rewritten by Paul Stoffregen... + Copyright (c) 2009-10 Hernando Barragan. All right reserved. + Copyright 2011, Paul Stoffregen, paul@pjrc.com + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef String_class_h +#define String_class_h +#ifdef __cplusplus + +#include +#include +#include +#include + +// When compiling programs with this class, the following gcc parameters +// dramatically increase performance and memory (RAM) efficiency, typically +// with little or no increase in code size. +// -felide-constructors +// -std=c++0x + +class __FlashStringHelper; +#define F(string_literal) (reinterpret_cast(PSTR(string_literal))) + +// An inherited class for holding the result of a concatenation. These +// result objects are assumed to be writable by subsequent concatenations. +class StringSumHelper; + +// The string class +class String +{ + // use a function pointer to allow for "if (s)" without the + // complications of an operator bool(). for more information, see: + // http://www.artima.com/cppsource/safebool.html + typedef void (String::*StringIfHelperType)() const; + void StringIfHelper() const {} + +public: + // constructors + // creates a copy of the initial value. + // if the initial value is null or invalid, or if memory allocation + // fails, the string will be marked as invalid (i.e. "if (s)" will + // be false). + String(const char *cstr = ""); + String(const String &str); + #ifdef __GXX_EXPERIMENTAL_CXX0X__ + String(String &&rval); + String(StringSumHelper &&rval); + #endif + explicit String(char c); + explicit String(unsigned char, unsigned char base=10); + explicit String(int, unsigned char base=10); + explicit String(unsigned int, unsigned char base=10); + explicit String(long, unsigned char base=10); + explicit String(unsigned long, unsigned char base=10); + ~String(void); + + // memory management + // return true on success, false on failure (in which case, the string + // is left unchanged). reserve(0), if successful, will validate an + // invalid string (i.e., "if (s)" will be true afterwards) + unsigned char reserve(unsigned int size); + inline unsigned int length(void) const {return len;} + + // creates a copy of the assigned value. if the value is null or + // invalid, or if the memory allocation fails, the string will be + // marked as invalid ("if (s)" will be false). + String & operator = (const String &rhs); + String & operator = (const char *cstr); + #ifdef __GXX_EXPERIMENTAL_CXX0X__ + String & operator = (String &&rval); + String & operator = (StringSumHelper &&rval); + #endif + + // concatenate (works w/ built-in types) + + // returns true on success, false on failure (in which case, the string + // is left unchanged). if the argument is null or invalid, the + // concatenation is considered unsucessful. + unsigned char concat(const String &str); + unsigned char concat(const char *cstr); + unsigned char concat(char c); + unsigned char concat(unsigned char c); + unsigned char concat(int num); + unsigned char concat(unsigned int num); + unsigned char concat(long num); + unsigned char concat(unsigned long num); + + // if there's not enough memory for the concatenated value, the string + // will be left unchanged (but this isn't signalled in any way) + String & operator += (const String &rhs) {concat(rhs); return (*this);} + String & operator += (const char *cstr) {concat(cstr); return (*this);} + String & operator += (char c) {concat(c); return (*this);} + String & operator += (unsigned char num) {concat(num); return (*this);} + String & operator += (int num) {concat(num); return (*this);} + String & operator += (unsigned int num) {concat(num); return (*this);} + String & operator += (long num) {concat(num); return (*this);} + String & operator += (unsigned long num) {concat(num); return (*this);} + + friend StringSumHelper & operator + (const StringSumHelper &lhs, const String &rhs); + friend StringSumHelper & operator + (const StringSumHelper &lhs, const char *cstr); + friend StringSumHelper & operator + (const StringSumHelper &lhs, char c); + friend StringSumHelper & operator + (const StringSumHelper &lhs, unsigned char num); + friend StringSumHelper & operator + (const StringSumHelper &lhs, int num); + friend StringSumHelper & operator + (const StringSumHelper &lhs, unsigned int num); + friend StringSumHelper & operator + (const StringSumHelper &lhs, long num); + friend StringSumHelper & operator + (const StringSumHelper &lhs, unsigned long num); + + // comparison (only works w/ Strings and "strings") + operator StringIfHelperType() const { return buffer ? &String::StringIfHelper : 0; } + int compareTo(const String &s) const; + unsigned char equals(const String &s) const; + unsigned char equals(const char *cstr) const; + unsigned char operator == (const String &rhs) const {return equals(rhs);} + unsigned char operator == (const char *cstr) const {return equals(cstr);} + unsigned char operator != (const String &rhs) const {return !equals(rhs);} + unsigned char operator != (const char *cstr) const {return !equals(cstr);} + unsigned char operator < (const String &rhs) const; + unsigned char operator > (const String &rhs) const; + unsigned char operator <= (const String &rhs) const; + unsigned char operator >= (const String &rhs) const; + unsigned char equalsIgnoreCase(const String &s) const; + unsigned char startsWith( const String &prefix) const; + unsigned char startsWith(const String &prefix, unsigned int offset) const; + unsigned char endsWith(const String &suffix) const; + + // character acccess + char charAt(unsigned int index) const; + void setCharAt(unsigned int index, char c); + char operator [] (unsigned int index) const; + char& operator [] (unsigned int index); + void getBytes(unsigned char *buf, unsigned int bufsize, unsigned int index=0) const; + void toCharArray(char *buf, unsigned int bufsize, unsigned int index=0) const + {getBytes((unsigned char *)buf, bufsize, index);} + const char * c_str() const { return buffer; } + + // search + int indexOf( char ch ) const; + int indexOf( char ch, unsigned int fromIndex ) const; + int indexOf( const String &str ) const; + int indexOf( const String &str, unsigned int fromIndex ) const; + int lastIndexOf( char ch ) const; + int lastIndexOf( char ch, unsigned int fromIndex ) const; + int lastIndexOf( const String &str ) const; + int lastIndexOf( const String &str, unsigned int fromIndex ) const; + String substring( unsigned int beginIndex ) const; + String substring( unsigned int beginIndex, unsigned int endIndex ) const; + + // modification + void replace(char find, char replace); + void replace(const String& find, const String& replace); + void toLowerCase(void); + void toUpperCase(void); + void trim(void); + + // parsing/conversion + long toInt(void) const; + +protected: + char *buffer; // the actual char array + unsigned int capacity; // the array length minus one (for the '\0') + unsigned int len; // the String length (not counting the '\0') + unsigned char flags; // unused, for future features +protected: + void init(void); + void invalidate(void); + unsigned char changeBuffer(unsigned int maxStrLen); + unsigned char concat(const char *cstr, unsigned int length); + + // copy and move + String & copy(const char *cstr, unsigned int length); + #ifdef __GXX_EXPERIMENTAL_CXX0X__ + void move(String &rhs); + #endif +}; + +class StringSumHelper : public String +{ +public: + StringSumHelper(const String &s) : String(s) {} + StringSumHelper(const char *p) : String(p) {} + StringSumHelper(char c) : String(c) {} + StringSumHelper(unsigned char num) : String(num) {} + StringSumHelper(int num) : String(num) {} + StringSumHelper(unsigned int num) : String(num) {} + StringSumHelper(long num) : String(num) {} + StringSumHelper(unsigned long num) : String(num) {} +}; + +#endif // __cplusplus +#endif // String_class_h diff --git a/hardware/arduino/cores/robot/binary.h b/hardware/arduino/cores/robot/binary.h new file mode 100644 index 00000000000..aec4c733d4c --- /dev/null +++ b/hardware/arduino/cores/robot/binary.h @@ -0,0 +1,534 @@ +/* + binary.h - Definitions for binary constants + Copyright (c) 2006 David A. Mellis. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef Binary_h +#define Binary_h + +#define B0 0 +#define B00 0 +#define B000 0 +#define B0000 0 +#define B00000 0 +#define B000000 0 +#define B0000000 0 +#define B00000000 0 +#define B1 1 +#define B01 1 +#define B001 1 +#define B0001 1 +#define B00001 1 +#define B000001 1 +#define B0000001 1 +#define B00000001 1 +#define B10 2 +#define B010 2 +#define B0010 2 +#define B00010 2 +#define B000010 2 +#define B0000010 2 +#define B00000010 2 +#define B11 3 +#define B011 3 +#define B0011 3 +#define B00011 3 +#define B000011 3 +#define B0000011 3 +#define B00000011 3 +#define B100 4 +#define B0100 4 +#define B00100 4 +#define B000100 4 +#define B0000100 4 +#define B00000100 4 +#define B101 5 +#define B0101 5 +#define B00101 5 +#define B000101 5 +#define B0000101 5 +#define B00000101 5 +#define B110 6 +#define B0110 6 +#define B00110 6 +#define B000110 6 +#define B0000110 6 +#define B00000110 6 +#define B111 7 +#define B0111 7 +#define B00111 7 +#define B000111 7 +#define B0000111 7 +#define B00000111 7 +#define B1000 8 +#define B01000 8 +#define B001000 8 +#define B0001000 8 +#define B00001000 8 +#define B1001 9 +#define B01001 9 +#define B001001 9 +#define B0001001 9 +#define B00001001 9 +#define B1010 10 +#define B01010 10 +#define B001010 10 +#define B0001010 10 +#define B00001010 10 +#define B1011 11 +#define B01011 11 +#define B001011 11 +#define B0001011 11 +#define B00001011 11 +#define B1100 12 +#define B01100 12 +#define B001100 12 +#define B0001100 12 +#define B00001100 12 +#define B1101 13 +#define B01101 13 +#define B001101 13 +#define B0001101 13 +#define B00001101 13 +#define B1110 14 +#define B01110 14 +#define B001110 14 +#define B0001110 14 +#define B00001110 14 +#define B1111 15 +#define B01111 15 +#define B001111 15 +#define B0001111 15 +#define B00001111 15 +#define B10000 16 +#define B010000 16 +#define B0010000 16 +#define B00010000 16 +#define B10001 17 +#define B010001 17 +#define B0010001 17 +#define B00010001 17 +#define B10010 18 +#define B010010 18 +#define B0010010 18 +#define B00010010 18 +#define B10011 19 +#define B010011 19 +#define B0010011 19 +#define B00010011 19 +#define B10100 20 +#define B010100 20 +#define B0010100 20 +#define B00010100 20 +#define B10101 21 +#define B010101 21 +#define B0010101 21 +#define B00010101 21 +#define B10110 22 +#define B010110 22 +#define B0010110 22 +#define B00010110 22 +#define B10111 23 +#define B010111 23 +#define B0010111 23 +#define B00010111 23 +#define B11000 24 +#define B011000 24 +#define B0011000 24 +#define B00011000 24 +#define B11001 25 +#define B011001 25 +#define B0011001 25 +#define B00011001 25 +#define B11010 26 +#define B011010 26 +#define B0011010 26 +#define B00011010 26 +#define B11011 27 +#define B011011 27 +#define B0011011 27 +#define B00011011 27 +#define B11100 28 +#define B011100 28 +#define B0011100 28 +#define B00011100 28 +#define B11101 29 +#define B011101 29 +#define B0011101 29 +#define B00011101 29 +#define B11110 30 +#define B011110 30 +#define B0011110 30 +#define B00011110 30 +#define B11111 31 +#define B011111 31 +#define B0011111 31 +#define B00011111 31 +#define B100000 32 +#define B0100000 32 +#define B00100000 32 +#define B100001 33 +#define B0100001 33 +#define B00100001 33 +#define B100010 34 +#define B0100010 34 +#define B00100010 34 +#define B100011 35 +#define B0100011 35 +#define B00100011 35 +#define B100100 36 +#define B0100100 36 +#define B00100100 36 +#define B100101 37 +#define B0100101 37 +#define B00100101 37 +#define B100110 38 +#define B0100110 38 +#define B00100110 38 +#define B100111 39 +#define B0100111 39 +#define B00100111 39 +#define B101000 40 +#define B0101000 40 +#define B00101000 40 +#define B101001 41 +#define B0101001 41 +#define B00101001 41 +#define B101010 42 +#define B0101010 42 +#define B00101010 42 +#define B101011 43 +#define B0101011 43 +#define B00101011 43 +#define B101100 44 +#define B0101100 44 +#define B00101100 44 +#define B101101 45 +#define B0101101 45 +#define B00101101 45 +#define B101110 46 +#define B0101110 46 +#define B00101110 46 +#define B101111 47 +#define B0101111 47 +#define B00101111 47 +#define B110000 48 +#define B0110000 48 +#define B00110000 48 +#define B110001 49 +#define B0110001 49 +#define B00110001 49 +#define B110010 50 +#define B0110010 50 +#define B00110010 50 +#define B110011 51 +#define B0110011 51 +#define B00110011 51 +#define B110100 52 +#define B0110100 52 +#define B00110100 52 +#define B110101 53 +#define B0110101 53 +#define B00110101 53 +#define B110110 54 +#define B0110110 54 +#define B00110110 54 +#define B110111 55 +#define B0110111 55 +#define B00110111 55 +#define B111000 56 +#define B0111000 56 +#define B00111000 56 +#define B111001 57 +#define B0111001 57 +#define B00111001 57 +#define B111010 58 +#define B0111010 58 +#define B00111010 58 +#define B111011 59 +#define B0111011 59 +#define B00111011 59 +#define B111100 60 +#define B0111100 60 +#define B00111100 60 +#define B111101 61 +#define B0111101 61 +#define B00111101 61 +#define B111110 62 +#define B0111110 62 +#define B00111110 62 +#define B111111 63 +#define B0111111 63 +#define B00111111 63 +#define B1000000 64 +#define B01000000 64 +#define B1000001 65 +#define B01000001 65 +#define B1000010 66 +#define B01000010 66 +#define B1000011 67 +#define B01000011 67 +#define B1000100 68 +#define B01000100 68 +#define B1000101 69 +#define B01000101 69 +#define B1000110 70 +#define B01000110 70 +#define B1000111 71 +#define B01000111 71 +#define B1001000 72 +#define B01001000 72 +#define B1001001 73 +#define B01001001 73 +#define B1001010 74 +#define B01001010 74 +#define B1001011 75 +#define B01001011 75 +#define B1001100 76 +#define B01001100 76 +#define B1001101 77 +#define B01001101 77 +#define B1001110 78 +#define B01001110 78 +#define B1001111 79 +#define B01001111 79 +#define B1010000 80 +#define B01010000 80 +#define B1010001 81 +#define B01010001 81 +#define B1010010 82 +#define B01010010 82 +#define B1010011 83 +#define B01010011 83 +#define B1010100 84 +#define B01010100 84 +#define B1010101 85 +#define B01010101 85 +#define B1010110 86 +#define B01010110 86 +#define B1010111 87 +#define B01010111 87 +#define B1011000 88 +#define B01011000 88 +#define B1011001 89 +#define B01011001 89 +#define B1011010 90 +#define B01011010 90 +#define B1011011 91 +#define B01011011 91 +#define B1011100 92 +#define B01011100 92 +#define B1011101 93 +#define B01011101 93 +#define B1011110 94 +#define B01011110 94 +#define B1011111 95 +#define B01011111 95 +#define B1100000 96 +#define B01100000 96 +#define B1100001 97 +#define B01100001 97 +#define B1100010 98 +#define B01100010 98 +#define B1100011 99 +#define B01100011 99 +#define B1100100 100 +#define B01100100 100 +#define B1100101 101 +#define B01100101 101 +#define B1100110 102 +#define B01100110 102 +#define B1100111 103 +#define B01100111 103 +#define B1101000 104 +#define B01101000 104 +#define B1101001 105 +#define B01101001 105 +#define B1101010 106 +#define B01101010 106 +#define B1101011 107 +#define B01101011 107 +#define B1101100 108 +#define B01101100 108 +#define B1101101 109 +#define B01101101 109 +#define B1101110 110 +#define B01101110 110 +#define B1101111 111 +#define B01101111 111 +#define B1110000 112 +#define B01110000 112 +#define B1110001 113 +#define B01110001 113 +#define B1110010 114 +#define B01110010 114 +#define B1110011 115 +#define B01110011 115 +#define B1110100 116 +#define B01110100 116 +#define B1110101 117 +#define B01110101 117 +#define B1110110 118 +#define B01110110 118 +#define B1110111 119 +#define B01110111 119 +#define B1111000 120 +#define B01111000 120 +#define B1111001 121 +#define B01111001 121 +#define B1111010 122 +#define B01111010 122 +#define B1111011 123 +#define B01111011 123 +#define B1111100 124 +#define B01111100 124 +#define B1111101 125 +#define B01111101 125 +#define B1111110 126 +#define B01111110 126 +#define B1111111 127 +#define B01111111 127 +#define B10000000 128 +#define B10000001 129 +#define B10000010 130 +#define B10000011 131 +#define B10000100 132 +#define B10000101 133 +#define B10000110 134 +#define B10000111 135 +#define B10001000 136 +#define B10001001 137 +#define B10001010 138 +#define B10001011 139 +#define B10001100 140 +#define B10001101 141 +#define B10001110 142 +#define B10001111 143 +#define B10010000 144 +#define B10010001 145 +#define B10010010 146 +#define B10010011 147 +#define B10010100 148 +#define B10010101 149 +#define B10010110 150 +#define B10010111 151 +#define B10011000 152 +#define B10011001 153 +#define B10011010 154 +#define B10011011 155 +#define B10011100 156 +#define B10011101 157 +#define B10011110 158 +#define B10011111 159 +#define B10100000 160 +#define B10100001 161 +#define B10100010 162 +#define B10100011 163 +#define B10100100 164 +#define B10100101 165 +#define B10100110 166 +#define B10100111 167 +#define B10101000 168 +#define B10101001 169 +#define B10101010 170 +#define B10101011 171 +#define B10101100 172 +#define B10101101 173 +#define B10101110 174 +#define B10101111 175 +#define B10110000 176 +#define B10110001 177 +#define B10110010 178 +#define B10110011 179 +#define B10110100 180 +#define B10110101 181 +#define B10110110 182 +#define B10110111 183 +#define B10111000 184 +#define B10111001 185 +#define B10111010 186 +#define B10111011 187 +#define B10111100 188 +#define B10111101 189 +#define B10111110 190 +#define B10111111 191 +#define B11000000 192 +#define B11000001 193 +#define B11000010 194 +#define B11000011 195 +#define B11000100 196 +#define B11000101 197 +#define B11000110 198 +#define B11000111 199 +#define B11001000 200 +#define B11001001 201 +#define B11001010 202 +#define B11001011 203 +#define B11001100 204 +#define B11001101 205 +#define B11001110 206 +#define B11001111 207 +#define B11010000 208 +#define B11010001 209 +#define B11010010 210 +#define B11010011 211 +#define B11010100 212 +#define B11010101 213 +#define B11010110 214 +#define B11010111 215 +#define B11011000 216 +#define B11011001 217 +#define B11011010 218 +#define B11011011 219 +#define B11011100 220 +#define B11011101 221 +#define B11011110 222 +#define B11011111 223 +#define B11100000 224 +#define B11100001 225 +#define B11100010 226 +#define B11100011 227 +#define B11100100 228 +#define B11100101 229 +#define B11100110 230 +#define B11100111 231 +#define B11101000 232 +#define B11101001 233 +#define B11101010 234 +#define B11101011 235 +#define B11101100 236 +#define B11101101 237 +#define B11101110 238 +#define B11101111 239 +#define B11110000 240 +#define B11110001 241 +#define B11110010 242 +#define B11110011 243 +#define B11110100 244 +#define B11110101 245 +#define B11110110 246 +#define B11110111 247 +#define B11111000 248 +#define B11111001 249 +#define B11111010 250 +#define B11111011 251 +#define B11111100 252 +#define B11111101 253 +#define B11111110 254 +#define B11111111 255 + +#endif diff --git a/hardware/arduino/cores/robot/main.cpp b/hardware/arduino/cores/robot/main.cpp new file mode 100644 index 00000000000..0ad6962151c --- /dev/null +++ b/hardware/arduino/cores/robot/main.cpp @@ -0,0 +1,39 @@ +/* + main.cpp - Main loop for Arduino sketches + Copyright (c) 2005-2013 Arduino Team. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include + +int main(void) +{ + init(); + +#if defined(USBCON) + USBDevice.attach(); +#endif + + setup(); + + for (;;) { + loop(); + if (serialEventRun) serialEventRun(); + } + + return 0; +} + diff --git a/hardware/arduino/cores/robot/new.cpp b/hardware/arduino/cores/robot/new.cpp new file mode 100644 index 00000000000..b81031e90b8 --- /dev/null +++ b/hardware/arduino/cores/robot/new.cpp @@ -0,0 +1,28 @@ +#include + +void * operator new(size_t size) +{ + return malloc(size); +} + +void * operator new[](size_t size) +{ + return malloc(size); +} + +void operator delete(void * ptr) +{ + free(ptr); +} + +void operator delete[](void * ptr) +{ + free(ptr); +} + +int __cxa_guard_acquire(__guard *g) {return !*(char *)(g);}; +void __cxa_guard_release (__guard *g) {*(char *)g = 1;}; +void __cxa_guard_abort (__guard *) {}; + +void __cxa_pure_virtual(void) {}; + diff --git a/hardware/arduino/cores/robot/new.h b/hardware/arduino/cores/robot/new.h new file mode 100644 index 00000000000..991c86c7522 --- /dev/null +++ b/hardware/arduino/cores/robot/new.h @@ -0,0 +1,24 @@ +/* Header to define new/delete operators as they aren't provided by avr-gcc by default + Taken from http://www.avrfreaks.net/index.php?name=PNphpBB2&file=viewtopic&t=59453 + */ + +#ifndef NEW_H +#define NEW_H + +#include + +void * operator new(size_t size); +void * operator new[](size_t size); +void operator delete(void * ptr); +void operator delete[](void * ptr); + +__extension__ typedef int __guard __attribute__((mode (__DI__))); + +extern "C" int __cxa_guard_acquire(__guard *); +extern "C" void __cxa_guard_release (__guard *); +extern "C" void __cxa_guard_abort (__guard *); + +extern "C" void __cxa_pure_virtual(void); + +#endif + diff --git a/hardware/arduino/cores/robot/wiring.c b/hardware/arduino/cores/robot/wiring.c new file mode 100644 index 00000000000..a3c4390e3c8 --- /dev/null +++ b/hardware/arduino/cores/robot/wiring.c @@ -0,0 +1,324 @@ +/* + wiring.c - Partial implementation of the Wiring API for the ATmega8. + Part of Arduino - http://www.arduino.cc/ + + Copyright (c) 2005-2006 David A. Mellis + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA + + $Id$ +*/ + +#include "wiring_private.h" + +// the prescaler is set so that timer0 ticks every 64 clock cycles, and the +// the overflow handler is called every 256 ticks. +#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256)) + +// the whole number of milliseconds per timer0 overflow +#define MILLIS_INC (MICROSECONDS_PER_TIMER0_OVERFLOW / 1000) + +// the fractional number of milliseconds per timer0 overflow. we shift right +// by three to fit these numbers into a byte. (for the clock speeds we care +// about - 8 and 16 MHz - this doesn't lose precision.) +#define FRACT_INC ((MICROSECONDS_PER_TIMER0_OVERFLOW % 1000) >> 3) +#define FRACT_MAX (1000 >> 3) + +volatile unsigned long timer0_overflow_count = 0; +volatile unsigned long timer0_millis = 0; +static unsigned char timer0_fract = 0; + +#if defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__) +ISR(TIM0_OVF_vect) +#else +ISR(TIMER0_OVF_vect) +#endif +{ + // copy these to local variables so they can be stored in registers + // (volatile variables must be read from memory on every access) + unsigned long m = timer0_millis; + unsigned char f = timer0_fract; + + m += MILLIS_INC; + f += FRACT_INC; + if (f >= FRACT_MAX) { + f -= FRACT_MAX; + m += 1; + } + + timer0_fract = f; + timer0_millis = m; + timer0_overflow_count++; +} + +unsigned long millis() +{ + unsigned long m; + uint8_t oldSREG = SREG; + + // disable interrupts while we read timer0_millis or we might get an + // inconsistent value (e.g. in the middle of a write to timer0_millis) + cli(); + m = timer0_millis; + SREG = oldSREG; + + return m; +} + +unsigned long micros() { + unsigned long m; + uint8_t oldSREG = SREG, t; + + cli(); + m = timer0_overflow_count; +#if defined(TCNT0) + t = TCNT0; +#elif defined(TCNT0L) + t = TCNT0L; +#else + #error TIMER 0 not defined +#endif + + +#ifdef TIFR0 + if ((TIFR0 & _BV(TOV0)) && (t < 255)) + m++; +#else + if ((TIFR & _BV(TOV0)) && (t < 255)) + m++; +#endif + + SREG = oldSREG; + + return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond()); +} + +void delay(unsigned long ms) +{ + uint16_t start = (uint16_t)micros(); + + while (ms > 0) { + if (((uint16_t)micros() - start) >= 1000) { + ms--; + start += 1000; + } + } +} + +/* Delay for the given number of microseconds. Assumes a 8 or 16 MHz clock. */ +void delayMicroseconds(unsigned int us) +{ + // calling avrlib's delay_us() function with low values (e.g. 1 or + // 2 microseconds) gives delays longer than desired. + //delay_us(us); +#if F_CPU >= 20000000L + // for the 20 MHz clock on rare Arduino boards + + // for a one-microsecond delay, simply wait 2 cycle and return. The overhead + // of the function call yields a delay of exactly a one microsecond. + __asm__ __volatile__ ( + "nop" "\n\t" + "nop"); //just waiting 2 cycle + if (--us == 0) + return; + + // the following loop takes a 1/5 of a microsecond (4 cycles) + // per iteration, so execute it five times for each microsecond of + // delay requested. + us = (us<<2) + us; // x5 us + + // account for the time taken in the preceeding commands. + us -= 2; + +#elif F_CPU >= 16000000L + // for the 16 MHz clock on most Arduino boards + + // for a one-microsecond delay, simply return. the overhead + // of the function call yields a delay of approximately 1 1/8 us. + if (--us == 0) + return; + + // the following loop takes a quarter of a microsecond (4 cycles) + // per iteration, so execute it four times for each microsecond of + // delay requested. + us <<= 2; + + // account for the time taken in the preceeding commands. + us -= 2; +#else + // for the 8 MHz internal clock on the ATmega168 + + // for a one- or two-microsecond delay, simply return. the overhead of + // the function calls takes more than two microseconds. can't just + // subtract two, since us is unsigned; we'd overflow. + if (--us == 0) + return; + if (--us == 0) + return; + + // the following loop takes half of a microsecond (4 cycles) + // per iteration, so execute it twice for each microsecond of + // delay requested. + us <<= 1; + + // partially compensate for the time taken by the preceeding commands. + // we can't subtract any more than this or we'd overflow w/ small delays. + us--; +#endif + + // busy wait + __asm__ __volatile__ ( + "1: sbiw %0,1" "\n\t" // 2 cycles + "brne 1b" : "=w" (us) : "0" (us) // 2 cycles + ); +} + +void init() +{ + // this needs to be called before setup() or some functions won't + // work there + sei(); + + // on the ATmega168, timer 0 is also used for fast hardware pwm + // (using phase-correct PWM would mean that timer 0 overflowed half as often + // resulting in different millis() behavior on the ATmega8 and ATmega168) +#if defined(TCCR0A) && defined(WGM01) + sbi(TCCR0A, WGM01); + sbi(TCCR0A, WGM00); +#endif + + // set timer 0 prescale factor to 64 +#if defined(__AVR_ATmega128__) + // CPU specific: different values for the ATmega128 + sbi(TCCR0, CS02); +#elif defined(TCCR0) && defined(CS01) && defined(CS00) + // this combination is for the standard atmega8 + sbi(TCCR0, CS01); + sbi(TCCR0, CS00); +#elif defined(TCCR0B) && defined(CS01) && defined(CS00) + // this combination is for the standard 168/328/1280/2560 + sbi(TCCR0B, CS01); + sbi(TCCR0B, CS00); +#elif defined(TCCR0A) && defined(CS01) && defined(CS00) + // this combination is for the __AVR_ATmega645__ series + sbi(TCCR0A, CS01); + sbi(TCCR0A, CS00); +#else + #error Timer 0 prescale factor 64 not set correctly +#endif + + // enable timer 0 overflow interrupt +#if defined(TIMSK) && defined(TOIE0) + sbi(TIMSK, TOIE0); +#elif defined(TIMSK0) && defined(TOIE0) + sbi(TIMSK0, TOIE0); +#else + #error Timer 0 overflow interrupt not set correctly +#endif + + // timers 1 and 2 are used for phase-correct hardware pwm + // this is better for motors as it ensures an even waveform + // note, however, that fast pwm mode can achieve a frequency of up + // 8 MHz (with a 16 MHz clock) at 50% duty cycle + +#if defined(TCCR1B) && defined(CS11) && defined(CS10) + TCCR1B = 0; + + // set timer 1 prescale factor to 64 + sbi(TCCR1B, CS11); +#if F_CPU >= 8000000L + sbi(TCCR1B, CS10); +#endif +#elif defined(TCCR1) && defined(CS11) && defined(CS10) + sbi(TCCR1, CS11); +#if F_CPU >= 8000000L + sbi(TCCR1, CS10); +#endif +#endif + // put timer 1 in 8-bit phase correct pwm mode +#if defined(TCCR1A) && defined(WGM10) + sbi(TCCR1A, WGM10); +#elif defined(TCCR1) + #warning this needs to be finished +#endif + + // set timer 2 prescale factor to 64 +#if defined(TCCR2) && defined(CS22) + sbi(TCCR2, CS22); +#elif defined(TCCR2B) && defined(CS22) + sbi(TCCR2B, CS22); +#else + #warning Timer 2 not finished (may not be present on this CPU) +#endif + + // configure timer 2 for phase correct pwm (8-bit) +#if defined(TCCR2) && defined(WGM20) + sbi(TCCR2, WGM20); +#elif defined(TCCR2A) && defined(WGM20) + sbi(TCCR2A, WGM20); +#else + #warning Timer 2 not finished (may not be present on this CPU) +#endif + +#if defined(TCCR3B) && defined(CS31) && defined(WGM30) + sbi(TCCR3B, CS31); // set timer 3 prescale factor to 64 + sbi(TCCR3B, CS30); + sbi(TCCR3A, WGM30); // put timer 3 in 8-bit phase correct pwm mode +#endif + +#if defined(TCCR4A) && defined(TCCR4B) && defined(TCCR4D) /* beginning of timer4 block for 32U4 and similar */ + sbi(TCCR4B, CS42); // set timer4 prescale factor to 64 + sbi(TCCR4B, CS41); + sbi(TCCR4B, CS40); + sbi(TCCR4D, WGM40); // put timer 4 in phase- and frequency-correct PWM mode + sbi(TCCR4A, PWM4A); // enable PWM mode for comparator OCR4A + sbi(TCCR4C, PWM4D); // enable PWM mode for comparator OCR4D +#else /* beginning of timer4 block for ATMEGA1280 and ATMEGA2560 */ +#if defined(TCCR4B) && defined(CS41) && defined(WGM40) + sbi(TCCR4B, CS41); // set timer 4 prescale factor to 64 + sbi(TCCR4B, CS40); + sbi(TCCR4A, WGM40); // put timer 4 in 8-bit phase correct pwm mode +#endif +#endif /* end timer4 block for ATMEGA1280/2560 and similar */ + +#if defined(TCCR5B) && defined(CS51) && defined(WGM50) + sbi(TCCR5B, CS51); // set timer 5 prescale factor to 64 + sbi(TCCR5B, CS50); + sbi(TCCR5A, WGM50); // put timer 5 in 8-bit phase correct pwm mode +#endif + +#if defined(ADCSRA) + // set a2d prescale factor to 128 + // 16 MHz / 128 = 125 KHz, inside the desired 50-200 KHz range. + // XXX: this will not work properly for other clock speeds, and + // this code should use F_CPU to determine the prescale factor. + sbi(ADCSRA, ADPS2); + sbi(ADCSRA, ADPS1); + sbi(ADCSRA, ADPS0); + + // enable a2d conversions + sbi(ADCSRA, ADEN); +#endif + + // the bootloader connects pins 0 and 1 to the USART; disconnect them + // here so they can be used as normal digital i/o; they will be + // reconnected in Serial.begin() +#if defined(UCSRB) + UCSRB = 0; +#elif defined(UCSR0B) + UCSR0B = 0; +#endif +} diff --git a/hardware/arduino/cores/robot/wiring_analog.c b/hardware/arduino/cores/robot/wiring_analog.c new file mode 100644 index 00000000000..7ed0e4e1c4a --- /dev/null +++ b/hardware/arduino/cores/robot/wiring_analog.c @@ -0,0 +1,284 @@ +/* + wiring_analog.c - analog input and output + Part of Arduino - http://www.arduino.cc/ + + Copyright (c) 2005-2006 David A. Mellis + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA + + Modified 28 September 2010 by Mark Sproul + + $Id: wiring.c 248 2007-02-03 15:36:30Z mellis $ +*/ + +#include "wiring_private.h" +#include "pins_arduino.h" + +uint8_t analog_reference = DEFAULT; + +void analogReference(uint8_t mode) +{ + // can't actually set the register here because the default setting + // will connect AVCC and the AREF pin, which would cause a short if + // there's something connected to AREF. + analog_reference = mode; +} + +int analogRead(uint8_t pin) +{ + uint8_t low, high; + +#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) + if (pin >= 54) pin -= 54; // allow for channel or pin numbers +#elif defined(__AVR_ATmega32U4__) + if (pin >= 18) pin -= 18; // allow for channel or pin numbers +#elif defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega644__) || defined(__AVR_ATmega644A__) || defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644PA__) + if (pin >= 24) pin -= 24; // allow for channel or pin numbers +#elif defined(analogPinToChannel) && (defined(__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)) + pin = analogPinToChannel(pin); +#else + if (pin >= 14) pin -= 14; // allow for channel or pin numbers +#endif + +#if defined(__AVR_ATmega32U4__) + pin = analogPinToChannel(pin); + ADCSRB = (ADCSRB & ~(1 << MUX5)) | (((pin >> 3) & 0x01) << MUX5); +#elif defined(ADCSRB) && defined(MUX5) + // the MUX5 bit of ADCSRB selects whether we're reading from channels + // 0 to 7 (MUX5 low) or 8 to 15 (MUX5 high). + ADCSRB = (ADCSRB & ~(1 << MUX5)) | (((pin >> 3) & 0x01) << MUX5); +#endif + + // set the analog reference (high two bits of ADMUX) and select the + // channel (low 4 bits). this also sets ADLAR (left-adjust result) + // to 0 (the default). +#if defined(ADMUX) + ADMUX = (analog_reference << 6) | (pin & 0x07); +#endif + + // without a delay, we seem to read from the wrong channel + //delay(1); + +#if defined(ADCSRA) && defined(ADCL) + // start the conversion + sbi(ADCSRA, ADSC); + + // ADSC is cleared when the conversion finishes + while (bit_is_set(ADCSRA, ADSC)); + + // we have to read ADCL first; doing so locks both ADCL + // and ADCH until ADCH is read. reading ADCL second would + // cause the results of each conversion to be discarded, + // as ADCL and ADCH would be locked when it completed. + low = ADCL; + high = ADCH; +#else + // we dont have an ADC, return 0 + low = 0; + high = 0; +#endif + + // combine the two bytes + return (high << 8) | low; +} + +// Right now, PWM output only works on the pins with +// hardware support. These are defined in the appropriate +// pins_*.c file. For the rest of the pins, we default +// to digital output. +void analogWrite(uint8_t pin, int val) +{ + // We need to make sure the PWM output is enabled for those pins + // that support it, as we turn it off when digitally reading or + // writing with them. Also, make sure the pin is in output mode + // for consistenty with Wiring, which doesn't require a pinMode + // call for the analog output pins. + pinMode(pin, OUTPUT); + if (val == 0) + { + digitalWrite(pin, LOW); + } + else if (val == 255) + { + digitalWrite(pin, HIGH); + } + else + { + switch(digitalPinToTimer(pin)) + { + // XXX fix needed for atmega8 + #if defined(TCCR0) && defined(COM00) && !defined(__AVR_ATmega8__) + case TIMER0A: + // connect pwm to pin on timer 0 + sbi(TCCR0, COM00); + OCR0 = val; // set pwm duty + break; + #endif + + #if defined(TCCR0A) && defined(COM0A1) + case TIMER0A: + // connect pwm to pin on timer 0, channel A + sbi(TCCR0A, COM0A1); + OCR0A = val; // set pwm duty + break; + #endif + + #if defined(TCCR0A) && defined(COM0B1) + case TIMER0B: + // connect pwm to pin on timer 0, channel B + sbi(TCCR0A, COM0B1); + OCR0B = val; // set pwm duty + break; + #endif + + #if defined(TCCR1A) && defined(COM1A1) + case TIMER1A: + // connect pwm to pin on timer 1, channel A + sbi(TCCR1A, COM1A1); + OCR1A = val; // set pwm duty + break; + #endif + + #if defined(TCCR1A) && defined(COM1B1) + case TIMER1B: + // connect pwm to pin on timer 1, channel B + sbi(TCCR1A, COM1B1); + OCR1B = val; // set pwm duty + break; + #endif + + #if defined(TCCR2) && defined(COM21) + case TIMER2: + // connect pwm to pin on timer 2 + sbi(TCCR2, COM21); + OCR2 = val; // set pwm duty + break; + #endif + + #if defined(TCCR2A) && defined(COM2A1) + case TIMER2A: + // connect pwm to pin on timer 2, channel A + sbi(TCCR2A, COM2A1); + OCR2A = val; // set pwm duty + break; + #endif + + #if defined(TCCR2A) && defined(COM2B1) + case TIMER2B: + // connect pwm to pin on timer 2, channel B + sbi(TCCR2A, COM2B1); + OCR2B = val; // set pwm duty + break; + #endif + + #if defined(TCCR3A) && defined(COM3A1) + case TIMER3A: + // connect pwm to pin on timer 3, channel A + sbi(TCCR3A, COM3A1); + OCR3A = val; // set pwm duty + break; + #endif + + #if defined(TCCR3A) && defined(COM3B1) + case TIMER3B: + // connect pwm to pin on timer 3, channel B + sbi(TCCR3A, COM3B1); + OCR3B = val; // set pwm duty + break; + #endif + + #if defined(TCCR3A) && defined(COM3C1) + case TIMER3C: + // connect pwm to pin on timer 3, channel C + sbi(TCCR3A, COM3C1); + OCR3C = val; // set pwm duty + break; + #endif + + #if defined(TCCR4A) + case TIMER4A: + //connect pwm to pin on timer 4, channel A + sbi(TCCR4A, COM4A1); + #if defined(COM4A0) // only used on 32U4 + cbi(TCCR4A, COM4A0); + #endif + OCR4A = val; // set pwm duty + break; + #endif + + #if defined(TCCR4A) && defined(COM4B1) + case TIMER4B: + // connect pwm to pin on timer 4, channel B + sbi(TCCR4A, COM4B1); + OCR4B = val; // set pwm duty + break; + #endif + + #if defined(TCCR4A) && defined(COM4C1) + case TIMER4C: + // connect pwm to pin on timer 4, channel C + sbi(TCCR4A, COM4C1); + OCR4C = val; // set pwm duty + break; + #endif + + #if defined(TCCR4C) && defined(COM4D1) + case TIMER4D: + // connect pwm to pin on timer 4, channel D + sbi(TCCR4C, COM4D1); + #if defined(COM4D0) // only used on 32U4 + cbi(TCCR4C, COM4D0); + #endif + OCR4D = val; // set pwm duty + break; + #endif + + + #if defined(TCCR5A) && defined(COM5A1) + case TIMER5A: + // connect pwm to pin on timer 5, channel A + sbi(TCCR5A, COM5A1); + OCR5A = val; // set pwm duty + break; + #endif + + #if defined(TCCR5A) && defined(COM5B1) + case TIMER5B: + // connect pwm to pin on timer 5, channel B + sbi(TCCR5A, COM5B1); + OCR5B = val; // set pwm duty + break; + #endif + + #if defined(TCCR5A) && defined(COM5C1) + case TIMER5C: + // connect pwm to pin on timer 5, channel C + sbi(TCCR5A, COM5C1); + OCR5C = val; // set pwm duty + break; + #endif + + case NOT_ON_TIMER: + default: + if (val < 128) { + digitalWrite(pin, LOW); + } else { + digitalWrite(pin, HIGH); + } + } + } +} + diff --git a/hardware/arduino/cores/robot/wiring_digital.c b/hardware/arduino/cores/robot/wiring_digital.c new file mode 100644 index 00000000000..be323b1dfef --- /dev/null +++ b/hardware/arduino/cores/robot/wiring_digital.c @@ -0,0 +1,178 @@ +/* + wiring_digital.c - digital input and output functions + Part of Arduino - http://www.arduino.cc/ + + Copyright (c) 2005-2006 David A. Mellis + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA + + Modified 28 September 2010 by Mark Sproul + + $Id: wiring.c 248 2007-02-03 15:36:30Z mellis $ +*/ + +#define ARDUINO_MAIN +#include "wiring_private.h" +#include "pins_arduino.h" + +void pinMode(uint8_t pin, uint8_t mode) +{ + uint8_t bit = digitalPinToBitMask(pin); + uint8_t port = digitalPinToPort(pin); + volatile uint8_t *reg, *out; + + if (port == NOT_A_PIN) return; + + // JWS: can I let the optimizer do this? + reg = portModeRegister(port); + out = portOutputRegister(port); + + if (mode == INPUT) { + uint8_t oldSREG = SREG; + cli(); + *reg &= ~bit; + *out &= ~bit; + SREG = oldSREG; + } else if (mode == INPUT_PULLUP) { + uint8_t oldSREG = SREG; + cli(); + *reg &= ~bit; + *out |= bit; + SREG = oldSREG; + } else { + uint8_t oldSREG = SREG; + cli(); + *reg |= bit; + SREG = oldSREG; + } +} + +// Forcing this inline keeps the callers from having to push their own stuff +// on the stack. It is a good performance win and only takes 1 more byte per +// user than calling. (It will take more bytes on the 168.) +// +// But shouldn't this be moved into pinMode? Seems silly to check and do on +// each digitalread or write. +// +// Mark Sproul: +// - Removed inline. Save 170 bytes on atmega1280 +// - changed to a switch statment; added 32 bytes but much easier to read and maintain. +// - Added more #ifdefs, now compiles for atmega645 +// +//static inline void turnOffPWM(uint8_t timer) __attribute__ ((always_inline)); +//static inline void turnOffPWM(uint8_t timer) +static void turnOffPWM(uint8_t timer) +{ + switch (timer) + { + #if defined(TCCR1A) && defined(COM1A1) + case TIMER1A: cbi(TCCR1A, COM1A1); break; + #endif + #if defined(TCCR1A) && defined(COM1B1) + case TIMER1B: cbi(TCCR1A, COM1B1); break; + #endif + + #if defined(TCCR2) && defined(COM21) + case TIMER2: cbi(TCCR2, COM21); break; + #endif + + #if defined(TCCR0A) && defined(COM0A1) + case TIMER0A: cbi(TCCR0A, COM0A1); break; + #endif + + #if defined(TIMER0B) && defined(COM0B1) + case TIMER0B: cbi(TCCR0A, COM0B1); break; + #endif + #if defined(TCCR2A) && defined(COM2A1) + case TIMER2A: cbi(TCCR2A, COM2A1); break; + #endif + #if defined(TCCR2A) && defined(COM2B1) + case TIMER2B: cbi(TCCR2A, COM2B1); break; + #endif + + #if defined(TCCR3A) && defined(COM3A1) + case TIMER3A: cbi(TCCR3A, COM3A1); break; + #endif + #if defined(TCCR3A) && defined(COM3B1) + case TIMER3B: cbi(TCCR3A, COM3B1); break; + #endif + #if defined(TCCR3A) && defined(COM3C1) + case TIMER3C: cbi(TCCR3A, COM3C1); break; + #endif + + #if defined(TCCR4A) && defined(COM4A1) + case TIMER4A: cbi(TCCR4A, COM4A1); break; + #endif + #if defined(TCCR4A) && defined(COM4B1) + case TIMER4B: cbi(TCCR4A, COM4B1); break; + #endif + #if defined(TCCR4A) && defined(COM4C1) + case TIMER4C: cbi(TCCR4A, COM4C1); break; + #endif + #if defined(TCCR4C) && defined(COM4D1) + case TIMER4D: cbi(TCCR4C, COM4D1); break; + #endif + + #if defined(TCCR5A) + case TIMER5A: cbi(TCCR5A, COM5A1); break; + case TIMER5B: cbi(TCCR5A, COM5B1); break; + case TIMER5C: cbi(TCCR5A, COM5C1); break; + #endif + } +} + +void digitalWrite(uint8_t pin, uint8_t val) +{ + uint8_t timer = digitalPinToTimer(pin); + uint8_t bit = digitalPinToBitMask(pin); + uint8_t port = digitalPinToPort(pin); + volatile uint8_t *out; + + if (port == NOT_A_PIN) return; + + // If the pin that support PWM output, we need to turn it off + // before doing a digital write. + if (timer != NOT_ON_TIMER) turnOffPWM(timer); + + out = portOutputRegister(port); + + uint8_t oldSREG = SREG; + cli(); + + if (val == LOW) { + *out &= ~bit; + } else { + *out |= bit; + } + + SREG = oldSREG; +} + +int digitalRead(uint8_t pin) +{ + uint8_t timer = digitalPinToTimer(pin); + uint8_t bit = digitalPinToBitMask(pin); + uint8_t port = digitalPinToPort(pin); + + if (port == NOT_A_PIN) return LOW; + + // If the pin that support PWM output, we need to turn it off + // before getting a digital reading. + if (timer != NOT_ON_TIMER) turnOffPWM(timer); + + if (*portInputRegister(port) & bit) return HIGH; + return LOW; +} diff --git a/hardware/arduino/cores/robot/wiring_private.h b/hardware/arduino/cores/robot/wiring_private.h new file mode 100755 index 00000000000..c366005c416 --- /dev/null +++ b/hardware/arduino/cores/robot/wiring_private.h @@ -0,0 +1,71 @@ +/* + wiring_private.h - Internal header file. + Part of Arduino - http://www.arduino.cc/ + + Copyright (c) 2005-2006 David A. Mellis + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA + + $Id: wiring.h 239 2007-01-12 17:58:39Z mellis $ +*/ + +#ifndef WiringPrivate_h +#define WiringPrivate_h + +#include +#include +#include +#include + +#include "Arduino.h" + +#ifdef __cplusplus +extern "C"{ +#endif + +#ifndef cbi +#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit)) +#endif +#ifndef sbi +#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit)) +#endif + +#define EXTERNAL_INT_0 0 +#define EXTERNAL_INT_1 1 +#define EXTERNAL_INT_2 2 +#define EXTERNAL_INT_3 3 +#define EXTERNAL_INT_4 4 +#define EXTERNAL_INT_5 5 +#define EXTERNAL_INT_6 6 +#define EXTERNAL_INT_7 7 + +#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) +#define EXTERNAL_NUM_INTERRUPTS 8 +#elif defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega644__) || defined(__AVR_ATmega644A__) || defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644PA__) +#define EXTERNAL_NUM_INTERRUPTS 3 +#elif defined(__AVR_ATmega32U4__) +#define EXTERNAL_NUM_INTERRUPTS 5 +#else +#define EXTERNAL_NUM_INTERRUPTS 2 +#endif + +typedef void (*voidFuncPtr)(void); + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif diff --git a/hardware/arduino/cores/robot/wiring_pulse.c b/hardware/arduino/cores/robot/wiring_pulse.c new file mode 100755 index 00000000000..0d968865d2f --- /dev/null +++ b/hardware/arduino/cores/robot/wiring_pulse.c @@ -0,0 +1,69 @@ +/* + wiring_pulse.c - pulseIn() function + Part of Arduino - http://www.arduino.cc/ + + Copyright (c) 2005-2006 David A. Mellis + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA + + $Id: wiring.c 248 2007-02-03 15:36:30Z mellis $ +*/ + +#include "wiring_private.h" +#include "pins_arduino.h" + +/* Measures the length (in microseconds) of a pulse on the pin; state is HIGH + * or LOW, the type of pulse to measure. Works on pulses from 2-3 microseconds + * to 3 minutes in length, but must be called at least a few dozen microseconds + * before the start of the pulse. */ +unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout) +{ + // cache the port and bit of the pin in order to speed up the + // pulse width measuring loop and achieve finer resolution. calling + // digitalRead() instead yields much coarser resolution. + uint8_t bit = digitalPinToBitMask(pin); + uint8_t port = digitalPinToPort(pin); + uint8_t stateMask = (state ? bit : 0); + unsigned long width = 0; // keep initialization out of time critical area + + // convert the timeout from microseconds to a number of times through + // the initial loop; it takes 16 clock cycles per iteration. + unsigned long numloops = 0; + unsigned long maxloops = microsecondsToClockCycles(timeout) / 16; + + // wait for any previous pulse to end + while ((*portInputRegister(port) & bit) == stateMask) + if (numloops++ == maxloops) + return 0; + + // wait for the pulse to start + while ((*portInputRegister(port) & bit) != stateMask) + if (numloops++ == maxloops) + return 0; + + // wait for the pulse to stop + while ((*portInputRegister(port) & bit) == stateMask) { + if (numloops++ == maxloops) + return 0; + width++; + } + + // convert the reading to microseconds. The loop has been determined + // to be 20 clock cycles long and have about 16 clocks between the edge + // and the start of the loop. There will be some error introduced by + // the interrupt handlers. + return clockCyclesToMicroseconds(width * 21 + 16); +} diff --git a/hardware/arduino/cores/robot/wiring_shift.c b/hardware/arduino/cores/robot/wiring_shift.c new file mode 100755 index 00000000000..cfe786758c5 --- /dev/null +++ b/hardware/arduino/cores/robot/wiring_shift.c @@ -0,0 +1,55 @@ +/* + wiring_shift.c - shiftOut() function + Part of Arduino - http://www.arduino.cc/ + + Copyright (c) 2005-2006 David A. Mellis + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA + + $Id: wiring.c 248 2007-02-03 15:36:30Z mellis $ +*/ + +#include "wiring_private.h" + +uint8_t shiftIn(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder) { + uint8_t value = 0; + uint8_t i; + + for (i = 0; i < 8; ++i) { + digitalWrite(clockPin, HIGH); + if (bitOrder == LSBFIRST) + value |= digitalRead(dataPin) << i; + else + value |= digitalRead(dataPin) << (7 - i); + digitalWrite(clockPin, LOW); + } + return value; +} + +void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val) +{ + uint8_t i; + + for (i = 0; i < 8; i++) { + if (bitOrder == LSBFIRST) + digitalWrite(dataPin, !!(val & (1 << i))); + else + digitalWrite(dataPin, !!(val & (1 << (7 - i)))); + + digitalWrite(clockPin, HIGH); + digitalWrite(clockPin, LOW); + } +} diff --git a/hardware/arduino/variants/ethernet/pins_arduino.h b/hardware/arduino/variants/ethernet/pins_arduino.h new file mode 100644 index 00000000000..cdcb0ed2247 --- /dev/null +++ b/hardware/arduino/variants/ethernet/pins_arduino.h @@ -0,0 +1,236 @@ +/* + pins_arduino.h - Pin definition functions for Arduino + Part of Arduino - http://www.arduino.cc/ + + Copyright (c) 2007 David A. Mellis + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA + + $Id: wiring.h 249 2007-02-03 16:52:51Z mellis $ +*/ + +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define NUM_DIGITAL_PINS 20 +#define NUM_ANALOG_INPUTS 6 +#define analogInputToDigitalPin(p) ((p < 6) ? (p) + 14 : -1) + +#if defined(__AVR_ATmega8__) +#define digitalPinHasPWM(p) ((p) == 9 || (p) == 10 || (p) == 11) +#else +#define digitalPinHasPWM(p) ((p) == 3 || (p) == 5 || (p) == 6 || (p) == 9 || (p) == 10 || (p) == 11) +#endif + +static const uint8_t SS = 10; +static const uint8_t MOSI = 11; +static const uint8_t MISO = 12; +static const uint8_t SCK = 13; + +static const uint8_t SDA = 18; +static const uint8_t SCL = 19; +#define LED_BUILTIN 9 + +static const uint8_t A0 = 14; +static const uint8_t A1 = 15; +static const uint8_t A2 = 16; +static const uint8_t A3 = 17; +static const uint8_t A4 = 18; +static const uint8_t A5 = 19; +static const uint8_t A6 = 20; +static const uint8_t A7 = 21; + +#define digitalPinToPCICR(p) (((p) >= 0 && (p) <= 21) ? (&PCICR) : ((uint8_t *)0)) +#define digitalPinToPCICRbit(p) (((p) <= 7) ? 2 : (((p) <= 13) ? 0 : 1)) +#define digitalPinToPCMSK(p) (((p) <= 7) ? (&PCMSK2) : (((p) <= 13) ? (&PCMSK0) : (((p) <= 21) ? (&PCMSK1) : ((uint8_t *)0)))) +#define digitalPinToPCMSKbit(p) (((p) <= 7) ? (p) : (((p) <= 13) ? ((p) - 8) : ((p) - 14))) + +#ifdef ARDUINO_MAIN + +// On the Arduino board, digital pins are also used +// for the analog output (software PWM). Analog input +// pins are a separate set. + +// ATMEL ATMEGA8 & 168 / ARDUINO +// +// +-\/-+ +// PC6 1| |28 PC5 (AI 5) +// (D 0) PD0 2| |27 PC4 (AI 4) +// (D 1) PD1 3| |26 PC3 (AI 3) +// (D 2) PD2 4| |25 PC2 (AI 2) +// PWM+ (D 3) PD3 5| |24 PC1 (AI 1) +// (D 4) PD4 6| |23 PC0 (AI 0) +// VCC 7| |22 GND +// GND 8| |21 AREF +// PB6 9| |20 AVCC +// PB7 10| |19 PB5 (D 13) +// PWM+ (D 5) PD5 11| |18 PB4 (D 12) +// PWM+ (D 6) PD6 12| |17 PB3 (D 11) PWM +// (D 7) PD7 13| |16 PB2 (D 10) PWM +// (D 8) PB0 14| |15 PB1 (D 9) PWM +// +----+ +// +// (PWM+ indicates the additional PWM pins on the ATmega168.) + +// ATMEL ATMEGA1280 / ARDUINO +// +// 0-7 PE0-PE7 works +// 8-13 PB0-PB5 works +// 14-21 PA0-PA7 works +// 22-29 PH0-PH7 works +// 30-35 PG5-PG0 works +// 36-43 PC7-PC0 works +// 44-51 PJ7-PJ0 works +// 52-59 PL7-PL0 works +// 60-67 PD7-PD0 works +// A0-A7 PF0-PF7 +// A8-A15 PK0-PK7 + + +// these arrays map port names (e.g. port B) to the +// appropriate addresses for various functions (e.g. reading +// and writing) +const uint16_t PROGMEM port_to_mode_PGM[] = { + NOT_A_PORT, + NOT_A_PORT, + (uint16_t) &DDRB, + (uint16_t) &DDRC, + (uint16_t) &DDRD, +}; + +const uint16_t PROGMEM port_to_output_PGM[] = { + NOT_A_PORT, + NOT_A_PORT, + (uint16_t) &PORTB, + (uint16_t) &PORTC, + (uint16_t) &PORTD, +}; + +const uint16_t PROGMEM port_to_input_PGM[] = { + NOT_A_PORT, + NOT_A_PORT, + (uint16_t) &PINB, + (uint16_t) &PINC, + (uint16_t) &PIND, +}; + +const uint8_t PROGMEM digital_pin_to_port_PGM[] = { + PD, /* 0 */ + PD, + PD, + PD, + PD, + PD, + PD, + PD, + PB, /* 8 */ + PB, + PB, + PB, + PB, + PB, + PC, /* 14 */ + PC, + PC, + PC, + PC, + PC, +}; + +const uint8_t PROGMEM digital_pin_to_bit_mask_PGM[] = { + _BV(0), /* 0, port D */ + _BV(1), + _BV(2), + _BV(3), + _BV(4), + _BV(5), + _BV(6), + _BV(7), + _BV(0), /* 8, port B */ + _BV(1), + _BV(2), + _BV(3), + _BV(4), + _BV(5), + _BV(0), /* 14, port C */ + _BV(1), + _BV(2), + _BV(3), + _BV(4), + _BV(5), +}; + +const uint8_t PROGMEM digital_pin_to_timer_PGM[] = { + NOT_ON_TIMER, /* 0 - port D */ + NOT_ON_TIMER, + NOT_ON_TIMER, + // on the ATmega168, digital pin 3 has hardware pwm +#if defined(__AVR_ATmega8__) + NOT_ON_TIMER, +#else + TIMER2B, +#endif + NOT_ON_TIMER, + // on the ATmega168, digital pins 5 and 6 have hardware pwm +#if defined(__AVR_ATmega8__) + NOT_ON_TIMER, + NOT_ON_TIMER, +#else + TIMER0B, + TIMER0A, +#endif + NOT_ON_TIMER, + NOT_ON_TIMER, /* 8 - port B */ + TIMER1A, + TIMER1B, +#if defined(__AVR_ATmega8__) + TIMER2, +#else + TIMER2A, +#endif + NOT_ON_TIMER, + NOT_ON_TIMER, + NOT_ON_TIMER, + NOT_ON_TIMER, /* 14 - port C */ + NOT_ON_TIMER, + NOT_ON_TIMER, + NOT_ON_TIMER, + NOT_ON_TIMER, +}; + +#endif + +// These serial port names are intended to allow libraries and architecture-neutral +// sketches to automatically default to the correct port name for a particular type +// of use. For example, a GPS module would normally connect to SERIAL_PORT_HARDWARE_OPEN, +// the first hardware serial port whose RX/TX pins are not dedicated to another use. +// +// SERIAL_PORT_MONITOR Port which normally prints to the Arduino Serial Monitor +// +// SERIAL_PORT_USBVIRTUAL Port which is USB virtual serial +// +// SERIAL_PORT_LINUXBRIDGE Port which connects to a Linux system via Bridge library +// +// SERIAL_PORT_HARDWARE Hardware serial port, physical RX & TX pins. +// +// SERIAL_PORT_HARDWARE_OPEN Hardware serial ports which are open for use. Their RX & TX +// pins are NOT connected to anything by default. +#define SERIAL_PORT_HARDWARE Serial +#define SERIAL_PORT_HARDWARE_OPEN Serial + +#endif diff --git a/hardware/arduino/variants/leonardo/pins_arduino.h b/hardware/arduino/variants/leonardo/pins_arduino.h index 2c7f8372f45..473b92e3b51 100644 --- a/hardware/arduino/variants/leonardo/pins_arduino.h +++ b/hardware/arduino/variants/leonardo/pins_arduino.h @@ -101,6 +101,7 @@ static const uint8_t SDA = 2; static const uint8_t SCL = 3; +#define LED_BUILTIN 13 // Map SPI port to 'new' pins D14..D17 static const uint8_t SS = 17; @@ -334,4 +335,25 @@ const uint8_t PROGMEM analog_pin_to_channel_PGM[] = { }; #endif /* ARDUINO_MAIN */ + +// These serial port names are intended to allow libraries and architecture-neutral +// sketches to automatically default to the correct port name for a particular type +// of use. For example, a GPS module would normally connect to SERIAL_PORT_HARDWARE_OPEN, +// the first hardware serial port whose RX/TX pins are not dedicated to another use. +// +// SERIAL_PORT_MONITOR Port which normally prints to the Arduino Serial Monitor +// +// SERIAL_PORT_USBVIRTUAL Port which is USB virtual serial +// +// SERIAL_PORT_LINUXBRIDGE Port which connects to a Linux system via Bridge library +// +// SERIAL_PORT_HARDWARE Hardware serial port, physical RX & TX pins. +// +// SERIAL_PORT_HARDWARE_OPEN Hardware serial ports which are open for use. Their RX & TX +// pins are NOT connected to anything by default. +#define SERIAL_PORT_MONITOR Serial +#define SERIAL_PORT_USBVIRTUAL Serial +#define SERIAL_PORT_HARDWARE Serial1 +#define SERIAL_PORT_HARDWARE_OPEN Serial1 + #endif /* Pins_Arduino_h */ diff --git a/hardware/arduino/variants/mega/pins_arduino.h b/hardware/arduino/variants/mega/pins_arduino.h index 5a9b4cb09b5..9991a21c1d1 100644 --- a/hardware/arduino/variants/mega/pins_arduino.h +++ b/hardware/arduino/variants/mega/pins_arduino.h @@ -39,7 +39,7 @@ static const uint8_t SCK = 52; static const uint8_t SDA = 20; static const uint8_t SCL = 21; -static const uint8_t LED_BUILTIN = 13; +#define LED_BUILTIN 13 static const uint8_t A0 = 54; static const uint8_t A1 = 55; @@ -360,4 +360,28 @@ const uint8_t PROGMEM digital_pin_to_timer_PGM[] = { #endif -#endif \ No newline at end of file +// These serial port names are intended to allow libraries and architecture-neutral +// sketches to automatically default to the correct port name for a particular type +// of use. For example, a GPS module would normally connect to SERIAL_PORT_HARDWARE_OPEN, +// the first hardware serial port whose RX/TX pins are not dedicated to another use. +// +// SERIAL_PORT_MONITOR Port which normally prints to the Arduino Serial Monitor +// +// SERIAL_PORT_USBVIRTUAL Port which is USB virtual serial +// +// SERIAL_PORT_LINUXBRIDGE Port which connects to a Linux system via Bridge library +// +// SERIAL_PORT_HARDWARE Hardware serial port, physical RX & TX pins. +// +// SERIAL_PORT_HARDWARE_OPEN Hardware serial ports which are open for use. Their RX & TX +// pins are NOT connected to anything by default. +#define SERIAL_PORT_MONITOR Serial +#define SERIAL_PORT_HARDWARE Serial +#define SERIAL_PORT_HARDWARE1 Serial1 +#define SERIAL_PORT_HARDWARE2 Serial2 +#define SERIAL_PORT_HARDWARE3 Serial3 +#define SERIAL_PORT_HARDWARE_OPEN Serial1 +#define SERIAL_PORT_HARDWARE_OPEN1 Serial2 +#define SERIAL_PORT_HARDWARE_OPEN2 Serial3 + +#endif diff --git a/hardware/arduino/variants/robot_control/pins_arduino.h b/hardware/arduino/variants/robot_control/pins_arduino.h new file mode 100644 index 00000000000..4acfc0df8b3 --- /dev/null +++ b/hardware/arduino/variants/robot_control/pins_arduino.h @@ -0,0 +1,301 @@ +/* + pins_arduino.h - Pin definition functions for Arduino Robot Control Board + Part of Arduino - http://www.arduino.cc/ + + Copyright (c) 2913 D. Cuartielles, X. Yang (Arduino Verkstad) + Copyright (c) 2012 D. Cuartielles, N. de la Riva, I. Gallego, E. Gallego + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA + + $Id: pins_arduino.h 1 2013-03-16 20:47:51Z cuartielles $ +*/ + +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define ARDUINO_MODEL_USB_PID 0x0038 + +#define TX_RX_LED_INIT DDRD |= (1<<5), DDRB |= (1<<0) +#define TXLED0 PORTD |= (1<<5) +#define TXLED1 PORTD &= ~(1<<5) +#define RXLED0 PORTB |= (1<<0) +#define RXLED1 PORTB &= ~(1<<0) + +#define D0 TKD0 +#define D1 TKD1 +#define D2 TKD2 +#define D3 TKD3 +#define D4 TKD4 +#define D5 TKD5 + +static const uint8_t RX = 0; +static const uint8_t TX = 1; +static const uint8_t SDA = 2; +static const uint8_t SCL = 3; + +// Map SPI port to 'new' pins D14..D17 +static const uint8_t SS = 17; +static const uint8_t MOSI = 16; +static const uint8_t MISO = 14; +static const uint8_t SCK = 15; + +// Mapping of analog pins as digital I/O +// A6-A11 share with digital pins +static const uint8_t A0 = 18; +static const uint8_t A1 = 19; +static const uint8_t A2 = 20; +static const uint8_t A3 = 21; +static const uint8_t A4 = 22; +static const uint8_t A5 = 23; +static const uint8_t A6 = 24; // D4 +static const uint8_t A7 = 25; // D6 +static const uint8_t A8 = 26; // D8 +static const uint8_t A9 = 27; // D9 +static const uint8_t A10 = 28; // D10 +static const uint8_t A11 = 29; // D12 + +// Specific Mapping for the Control Board +static const uint8_t KEY = 18; // AD0 +static const uint8_t MUX_IN = 24; // ADC8 - A6 +static const uint8_t MUXA = 6; // D5 - TKD4 +static const uint8_t MUXB = 11; // D11 +static const uint8_t MUXC = 12; // D12 - TKD5 +static const uint8_t MUXD = 13; // D13 +static const uint8_t BUZZ = 5; // D5 +static const uint8_t POT = 23; // AD5 +static const uint8_t DC_LCD = 10; // D10 +static const uint8_t LCD_CS = 9; // D9 +static const uint8_t RST_LCD = 7; // D6 +static const uint8_t CARD_CS = 8; // D8 +static const uint8_t TKD0 = 19; // ADC6 - A1 +static const uint8_t TKD1 = 20; // ADC5 - A2 +static const uint8_t TKD2 = 21; // ADC4 - A3 +static const uint8_t TKD3 = 22; // ADC1 - A4 +static const uint8_t TKD4 = 6; // D5 - MUXA +static const uint8_t TKD5 = 12; // D12 - MUXC +static const uint8_t LED1 = 17; // D17 - RX_Led + +// __AVR_ATmega32U4__ has an unusual mapping of pins to channels +extern const uint8_t PROGMEM analog_pin_to_channel_PGM[]; +#define analogPinToChannel(P) ( pgm_read_byte( analog_pin_to_channel_PGM + (P) ) ) + +#ifdef ARDUINO_MAIN + +// On the Arduino board, digital pins are also used +// for the analog output (software PWM). Analog input +// pins are a separate set. + +// ARDUINO LEONARDO / ARDUINO ROBOT CONTROL / ATMEGA 32U4 / FUNCTION / REGISTER +// +// D0 RX PD2 RX RXD1/INT2 +// D1 TX PD3 TX TXD1/INT3 +// D2 SDA PD1 SDA SDA/INT1 +// D3# SCL PD0 PWM8/SCL OC0B/SCL/INT0 +// D4 MUX_IN A6 PD4 ADC8 +// D5# BUZZ PC6 ??? OC3A/#OC4A +// D6# MUXA/TKD4 A7 PD7 FastPWM #OC4D/ADC10 +// D7 RST_LCD PE6 INT6/AIN0 +// +// D8 CARD_CS A8 PB4 ADC11/PCINT4 +// D9# LCD_CS A9 PB5 PWM16 OC1A/#OC4B/ADC12/PCINT5 +// D10# DC_LCD A10 PB6 PWM16 OC1B/0c4B/ADC13/PCINT6 +// D11# MUXB PB7 PWM8/16 0C0A/OC1C/#RTS/PCINT7 +// D12 MUXC/TKD5 A11 PD6 T1/#OC4D/ADC9 +// D13# MUXD PC7 PWM10 CLK0/OC4A +// +// A0 KEY D18 PF7 ADC7 +// A1 TKD0 D19 PF6 ADC6 +// A2 TKD1 D20 PF5 ADC5 +// A3 TKD2 D21 PF4 ADC4 +// A4 TKD3 D22 PF1 ADC1 +// A5 POT D23 PF0 ADC0 +// +// MISO MISO D14 PB3 MISO,PCINT3 +// SCK SCK D15 PB1 SCK,PCINT1 +// MOSI MOSI D16 PB2 MOSI,PCINT2 +// SS RX_LED D17 PB0 RXLED,SS/PCINT0 +// +// TXLED TX_LED PD5 +// HWB PE2 HWB + +// these arrays map port names (e.g. port B) to the +// appropriate addresses for various functions (e.g. reading +// and writing) +const uint16_t PROGMEM port_to_mode_PGM[] = { + NOT_A_PORT, + NOT_A_PORT, + (uint16_t) &DDRB, + (uint16_t) &DDRC, + (uint16_t) &DDRD, + (uint16_t) &DDRE, + (uint16_t) &DDRF, +}; + +const uint16_t PROGMEM port_to_output_PGM[] = { + NOT_A_PORT, + NOT_A_PORT, + (uint16_t) &PORTB, + (uint16_t) &PORTC, + (uint16_t) &PORTD, + (uint16_t) &PORTE, + (uint16_t) &PORTF, +}; + +const uint16_t PROGMEM port_to_input_PGM[] = { + NOT_A_PORT, + NOT_A_PORT, + (uint16_t) &PINB, + (uint16_t) &PINC, + (uint16_t) &PIND, + (uint16_t) &PINE, + (uint16_t) &PINF, +}; + +const uint8_t PROGMEM digital_pin_to_port_PGM[30] = { + PD, // D0 - PD2 + PD, // D1 - PD3 + PD, // D2 - PD1 + PD, // D3 - PD0 + PD, // D4 - PD4 + PC, // D5 - PC6 + PD, // D6 - PD7 + PE, // D7 - PE6 + + PB, // D8 - PB4 + PB, // D9 - PB5 + PB, // D10 - PB6 + PB, // D11 - PB7 + PD, // D12 - PD6 + PC, // D13 - PC7 + + PB, // D14 - MISO - PB3 + PB, // D15 - SCK - PB1 + PB, // D16 - MOSI - PB2 + PB, // D17 - SS - PB0 + + PF, // D18 - A0 - PF7 + PF, // D19 - A1 - PF6 + PF, // D20 - A2 - PF5 + PF, // D21 - A3 - PF4 + PF, // D22 - A4 - PF1 + PF, // D23 - A5 - PF0 + + PD, // D24 / D4 - A6 - PD4 + PD, // D25 / D6 - A7 - PD7 + PB, // D26 / D8 - A8 - PB4 + PB, // D27 / D9 - A9 - PB5 + PB, // D28 / D10 - A10 - PB6 + PD, // D29 / D12 - A11 - PD6 +}; + +const uint8_t PROGMEM digital_pin_to_bit_mask_PGM[30] = { + _BV(2), // D0 - PD2 + _BV(3), // D1 - PD3 + _BV(1), // D2 - PD1 + _BV(0), // D3 - PD0 + _BV(4), // D4 - PD4 + _BV(6), // D5 - PC6 + _BV(7), // D6 - PD7 + _BV(6), // D7 - PE6 + + _BV(4), // D8 - PB4 + _BV(5), // D9 - PB5 + _BV(6), // D10 - PB6 + _BV(7), // D11 - PB7 + _BV(6), // D12 - PD6 + _BV(7), // D13 - PC7 + + _BV(3), // D14 - MISO - PB3 + _BV(1), // D15 - SCK - PB1 + _BV(2), // D16 - MOSI - PB2 + _BV(0), // D17 - SS - PB0 + + _BV(7), // D18 - A0 - PF7 + _BV(6), // D19 - A1 - PF6 + _BV(5), // D20 - A2 - PF5 + _BV(4), // D21 - A3 - PF4 + _BV(1), // D22 - A4 - PF1 + _BV(0), // D23 - A5 - PF0 + + _BV(4), // D24 / D4 - A6 - PD4 + _BV(7), // D25 / D6 - A7 - PD7 + _BV(4), // D26 / D8 - A8 - PB4 + _BV(5), // D27 / D9 - A9 - PB5 + _BV(6), // D28 / D10 - A10 - PB6 + _BV(6), // D29 / D12 - A11 - PD6 +}; + +const uint8_t PROGMEM digital_pin_to_timer_PGM[18] = { + NOT_ON_TIMER, + NOT_ON_TIMER, + NOT_ON_TIMER, + TIMER0B, /* 3 */ + NOT_ON_TIMER, + TIMER3A, /* 5 */ + TIMER4D, /* 6 */ + NOT_ON_TIMER, + + NOT_ON_TIMER, + TIMER1A, /* 9 */ + TIMER1B, /* 10 */ + TIMER0A, /* 11 */ + + NOT_ON_TIMER, + TIMER4A, /* 13 */ + + NOT_ON_TIMER, + NOT_ON_TIMER, +}; + +const uint8_t PROGMEM analog_pin_to_channel_PGM[12] = { + 7, // A0 PF7 ADC7 + 6, // A1 PF6 ADC6 + 5, // A2 PF5 ADC5 + 4, // A3 PF4 ADC4 + 1, // A4 PF1 ADC1 + 0, // A5 PF0 ADC0 + 8, // A6 D4 PD4 ADC8 + 10, // A7 D6 PD7 ADC10 + 11, // A8 D8 PB4 ADC11 + 12, // A9 D9 PB5 ADC12 + 13, // A10 D10 PB6 ADC13 + 9 // A11 D12 PD6 ADC9 +}; + +#endif /* ARDUINO_MAIN */ + +// These serial port names are intended to allow libraries and architecture-neutral +// sketches to automatically default to the correct port name for a particular type +// of use. For example, a GPS module would normally connect to SERIAL_PORT_HARDWARE_OPEN, +// the first hardware serial port whose RX/TX pins are not dedicated to another use. +// +// SERIAL_PORT_MONITOR Port which normally prints to the Arduino Serial Monitor +// +// SERIAL_PORT_USBVIRTUAL Port which is USB virtual serial +// +// SERIAL_PORT_LINUXBRIDGE Port which connects to a Linux system via Bridge library +// +// SERIAL_PORT_HARDWARE Hardware serial port, physical RX & TX pins. +// +// SERIAL_PORT_HARDWARE_OPEN Hardware serial ports which are open for use. Their RX & TX +// pins are NOT connected to anything by default. +#define SERIAL_PORT_MONITOR Serial +#define SERIAL_PORT_USBVIRTUAL Serial +#define SERIAL_PORT_HARDWARE Serial1 + +#endif /* Pins_Arduino_h */ diff --git a/hardware/arduino/variants/robot_motor/pins_arduino.h b/hardware/arduino/variants/robot_motor/pins_arduino.h new file mode 100644 index 00000000000..fdb4c6773c0 --- /dev/null +++ b/hardware/arduino/variants/robot_motor/pins_arduino.h @@ -0,0 +1,296 @@ +/* + pins_arduino.h - Pin definition functions for Arduino Robot Control Board + Part of Arduino - http://www.arduino.cc/ + + Copyright (c) 2913 D. Cuartielles, X. Yang (Arduino Verkstad) + Copyright (c) 2012 D. Cuartielles, N. de la Riva, I. Gallego, E. Gallego + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA + + $Id: pins_arduino.h 1 2013-03-16 20:47:51Z cuartielles $ +*/ + +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define ARDUINO_MODEL_USB_PID 0x0039 + +#define TX_RX_LED_INIT DDRD |= (1<<5), DDRB |= (1<<0) +#define TXLED0 PORTD |= (1<<5) +#define TXLED1 PORTD &= ~(1<<5) +#define RXLED0 PORTB |= (1<<0) +#define RXLED1 PORTB &= ~(1<<0) + +#define D10 TK1 +#define D9 TK2 +#define D8 TK4 +#define D7 TK3 + +static const uint8_t RX = 0; +static const uint8_t TX = 1; +static const uint8_t SDA = 2; +static const uint8_t SCL = 3; + +// Map SPI port to 'new' pins D14..D17 +static const uint8_t SS = 17; +static const uint8_t MOSI = 16; +static const uint8_t MISO = 14; +static const uint8_t SCK = 15; + +// Mapping of analog pins as digital I/O +// A6-A11 share with digital pins +static const uint8_t A0 = 18; +static const uint8_t A1 = 19; +static const uint8_t A2 = 20; +static const uint8_t A3 = 21; +static const uint8_t A4 = 22; +static const uint8_t A5 = 23; +static const uint8_t A6 = 24; // D4 +static const uint8_t A7 = 25; // D6 +static const uint8_t A8 = 26; // D8 +static const uint8_t A9 = 27; // D9 +static const uint8_t A10 = 28; // D10 +static const uint8_t A11 = 29; // D12 + +// Specific Mapping for the Motor Board +static const uint8_t MUX_IN = 20; // A2 +static const uint8_t MUXA = 7; // D7 +static const uint8_t MUXB = 8; // D8 +static const uint8_t MUXC = 11; // D11 +static const uint8_t MUXI = 13; // D13 +static const uint8_t TRIM = 21; // A3 +static const uint8_t SENSE_A = 22; // A4 +static const uint8_t SENSE_B = 23; // A5 +static const uint8_t IN_A1 = 6; // D6 - A7 +static const uint8_t IN_A2 = 5; // D5 +static const uint8_t IN_B1 = 10; // D10 +static const uint8_t IN_B2 = 9; // D9 +static const uint8_t TK1 = 18; // A0 +static const uint8_t TK2 = 19; // A1 +static const uint8_t TK3 = 4; // A6 +static const uint8_t TK4 = 12; // A11 + +// __AVR_ATmega32U4__ has an unusual mapping of pins to channels +extern const uint8_t PROGMEM analog_pin_to_channel_PGM[]; +#define analogPinToChannel(P) ( pgm_read_byte( analog_pin_to_channel_PGM + (P) ) ) + +#ifdef ARDUINO_MAIN + +// On the Arduino board, digital pins are also used +// for the analog output (software PWM). Analog input +// pins are a separate set. + +// ARDUINO LEONARDO / ARDUINO ROBOT CONTROL / ATMEGA 32U4 / FUNCTION / REGISTER +// +// D0 RX PD2 RX RXD1/INT2 +// D1 TX PD3 TX TXD1/INT3 +// D2 SDA PD1 SDA SDA/INT1 +// D3# SCL PD0 PWM8/SCL OC0B/SCL/INT0 +// D4 TK3 A6 PD4 ADC8 +// D5# INA2 PC6 ??? OC3A/#OC4A +// D6# INA1 A7 PD7 FastPWM #OC4D/ADC10 +// D7 MUXA PE6 INT6/AIN0 +// +// D8 MUXB A8 PB4 ADC11/PCINT4 +// D9# INB2 A9 PB5 PWM16 OC1A/#OC4B/ADC12/PCINT5 +// D10# INB1 A10 PB6 PWM16 OC1B/0c4B/ADC13/PCINT6 +// D11# MUXC PB7 PWM8/16 0C0A/OC1C/#RTS/PCINT7 +// D12 TK4 A11 PD6 T1/#OC4D/ADC9 +// D13# MUXI PC7 PWM10 CLK0/OC4A +// +// A0 TK1 D18 PF7 ADC7 +// A1 TK2 D19 PF6 ADC6 +// A2 MUX_IN D20 PF5 ADC5 +// A3 TRIM D21 PF4 ADC4 +// A4 SENSE_A D22 PF1 ADC1 +// A5 SENSE_B D23 PF0 ADC0 +// +// MISO MISO D14 PB3 MISO,PCINT3 +// SCK SCK D15 PB1 SCK,PCINT1 +// MOSI MOSI D16 PB2 MOSI,PCINT2 +// SS RX_LED D17 PB0 RXLED,SS/PCINT0 +// +// TXLED TX_LED PD5 +// HWB PE2 HWB + +// these arrays map port names (e.g. port B) to the +// appropriate addresses for various functions (e.g. reading +// and writing) +const uint16_t PROGMEM port_to_mode_PGM[] = { + NOT_A_PORT, + NOT_A_PORT, + (uint16_t) &DDRB, + (uint16_t) &DDRC, + (uint16_t) &DDRD, + (uint16_t) &DDRE, + (uint16_t) &DDRF, +}; + +const uint16_t PROGMEM port_to_output_PGM[] = { + NOT_A_PORT, + NOT_A_PORT, + (uint16_t) &PORTB, + (uint16_t) &PORTC, + (uint16_t) &PORTD, + (uint16_t) &PORTE, + (uint16_t) &PORTF, +}; + +const uint16_t PROGMEM port_to_input_PGM[] = { + NOT_A_PORT, + NOT_A_PORT, + (uint16_t) &PINB, + (uint16_t) &PINC, + (uint16_t) &PIND, + (uint16_t) &PINE, + (uint16_t) &PINF, +}; + +const uint8_t PROGMEM digital_pin_to_port_PGM[30] = { + PD, // D0 - PD2 + PD, // D1 - PD3 + PD, // D2 - PD1 + PD, // D3 - PD0 + PD, // D4 - PD4 + PC, // D5 - PC6 + PD, // D6 - PD7 + PE, // D7 - PE6 + + PB, // D8 - PB4 + PB, // D9 - PB5 + PB, // D10 - PB6 + PB, // D11 - PB7 + PD, // D12 - PD6 + PC, // D13 - PC7 + + PB, // D14 - MISO - PB3 + PB, // D15 - SCK - PB1 + PB, // D16 - MOSI - PB2 + PB, // D17 - SS - PB0 + + PF, // D18 - A0 - PF7 + PF, // D19 - A1 - PF6 + PF, // D20 - A2 - PF5 + PF, // D21 - A3 - PF4 + PF, // D22 - A4 - PF1 + PF, // D23 - A5 - PF0 + + PD, // D24 / D4 - A6 - PD4 + PD, // D25 / D6 - A7 - PD7 + PB, // D26 / D8 - A8 - PB4 + PB, // D27 / D9 - A9 - PB5 + PB, // D28 / D10 - A10 - PB6 + PD, // D29 / D12 - A11 - PD6 +}; + +const uint8_t PROGMEM digital_pin_to_bit_mask_PGM[30] = { + _BV(2), // D0 - PD2 + _BV(3), // D1 - PD3 + _BV(1), // D2 - PD1 + _BV(0), // D3 - PD0 + _BV(4), // D4 - PD4 + _BV(6), // D5 - PC6 + _BV(7), // D6 - PD7 + _BV(6), // D7 - PE6 + + _BV(4), // D8 - PB4 + _BV(5), // D9 - PB5 + _BV(6), // D10 - PB6 + _BV(7), // D11 - PB7 + _BV(6), // D12 - PD6 + _BV(7), // D13 - PC7 + + _BV(3), // D14 - MISO - PB3 + _BV(1), // D15 - SCK - PB1 + _BV(2), // D16 - MOSI - PB2 + _BV(0), // D17 - SS - PB0 + + _BV(7), // D18 - A0 - PF7 + _BV(6), // D19 - A1 - PF6 + _BV(5), // D20 - A2 - PF5 + _BV(4), // D21 - A3 - PF4 + _BV(1), // D22 - A4 - PF1 + _BV(0), // D23 - A5 - PF0 + + _BV(4), // D24 / D4 - A6 - PD4 + _BV(7), // D25 / D6 - A7 - PD7 + _BV(4), // D26 / D8 - A8 - PB4 + _BV(5), // D27 / D9 - A9 - PB5 + _BV(6), // D28 / D10 - A10 - PB6 + _BV(6), // D29 / D12 - A11 - PD6 +}; + +const uint8_t PROGMEM digital_pin_to_timer_PGM[18] = { + NOT_ON_TIMER, + NOT_ON_TIMER, + NOT_ON_TIMER, + TIMER0B, /* 3 */ + NOT_ON_TIMER, + TIMER3A, /* 5 */ + TIMER4D, /* 6 */ + NOT_ON_TIMER, + + NOT_ON_TIMER, + TIMER1A, /* 9 */ + TIMER1B, /* 10 */ + TIMER0A, /* 11 */ + + NOT_ON_TIMER, + TIMER4A, /* 13 */ + + NOT_ON_TIMER, + NOT_ON_TIMER, +}; + +const uint8_t PROGMEM analog_pin_to_channel_PGM[12] = { + 7, // A0 PF7 ADC7 + 6, // A1 PF6 ADC6 + 5, // A2 PF5 ADC5 + 4, // A3 PF4 ADC4 + 1, // A4 PF1 ADC1 + 0, // A5 PF0 ADC0 + 8, // A6 D4 PD4 ADC8 + 10, // A7 D6 PD7 ADC10 + 11, // A8 D8 PB4 ADC11 + 12, // A9 D9 PB5 ADC12 + 13, // A10 D10 PB6 ADC13 + 9 // A11 D12 PD6 ADC9 +}; + +#endif /* ARDUINO_MAIN */ + +// These serial port names are intended to allow libraries and architecture-neutral +// sketches to automatically default to the correct port name for a particular type +// of use. For example, a GPS module would normally connect to SERIAL_PORT_HARDWARE_OPEN, +// the first hardware serial port whose RX/TX pins are not dedicated to another use. +// +// SERIAL_PORT_MONITOR Port which normally prints to the Arduino Serial Monitor +// +// SERIAL_PORT_USBVIRTUAL Port which is USB virtual serial +// +// SERIAL_PORT_LINUXBRIDGE Port which connects to a Linux system via Bridge library +// +// SERIAL_PORT_HARDWARE Hardware serial port, physical RX & TX pins. +// +// SERIAL_PORT_HARDWARE_OPEN Hardware serial ports which are open for use. Their RX & TX +// pins are NOT connected to anything by default. +#define SERIAL_PORT_MONITOR Serial +#define SERIAL_PORT_USBVIRTUAL Serial +#define SERIAL_PORT_HARDWARE Serial1 + +#endif /* Pins_Arduino_h */ diff --git a/hardware/arduino/variants/standard/pins_arduino.h b/hardware/arduino/variants/standard/pins_arduino.h index 30b42663065..2e24e1979a0 100644 --- a/hardware/arduino/variants/standard/pins_arduino.h +++ b/hardware/arduino/variants/standard/pins_arduino.h @@ -44,7 +44,7 @@ static const uint8_t SCK = 13; static const uint8_t SDA = 18; static const uint8_t SCL = 19; -static const uint8_t LED_BUILTIN = 13; +#define LED_BUILTIN 13 static const uint8_t A0 = 14; static const uint8_t A1 = 15; @@ -215,4 +215,22 @@ const uint8_t PROGMEM digital_pin_to_timer_PGM[] = { #endif +// These serial port names are intended to allow libraries and architecture-neutral +// sketches to automatically default to the correct port name for a particular type +// of use. For example, a GPS module would normally connect to SERIAL_PORT_HARDWARE_OPEN, +// the first hardware serial port whose RX/TX pins are not dedicated to another use. +// +// SERIAL_PORT_MONITOR Port which normally prints to the Arduino Serial Monitor +// +// SERIAL_PORT_USBVIRTUAL Port which is USB virtual serial +// +// SERIAL_PORT_LINUXBRIDGE Port which connects to a Linux system via Bridge library +// +// SERIAL_PORT_HARDWARE Hardware serial port, physical RX & TX pins. +// +// SERIAL_PORT_HARDWARE_OPEN Hardware serial ports which are open for use. Their RX & TX +// pins are NOT connected to anything by default. +#define SERIAL_PORT_MONITOR Serial +#define SERIAL_PORT_HARDWARE Serial + #endif diff --git a/libraries/Esplora/Esplora.h b/libraries/Esplora/Esplora.h index 4f5534552bb..56f76ab3a89 100644 --- a/libraries/Esplora/Esplora.h +++ b/libraries/Esplora/Esplora.h @@ -40,6 +40,8 @@ const byte CH_SLIDER = 4; const byte CH_LIGHT = 5; const byte CH_TEMPERATURE = 6; const byte CH_MIC = 7; +const byte CH_TINKERKIT_A = 8; +const byte CH_TINKERKIT_B = 9; const byte CH_JOYSTICK_SW = 10; const byte CH_JOYSTICK_X = 11; const byte CH_JOYSTICK_Y = 12; @@ -156,6 +158,16 @@ class _Esplora { void tone(unsigned int freq); void tone(unsigned int freq, unsigned long duration); void noTone(); + + inline unsigned int readTinkerkitInput(byte whichInput) { + return readChannel(whichInput + CH_TINKERKIT_A); + } + inline unsigned int readTinkerkitInputA() { + return readChannel(CH_TINKERKIT_A); + } + inline unsigned int readTinkerkitInputB() { + return readChannel(CH_TINKERKIT_B); + } }; diff --git a/libraries/Esplora/examples/Beginners/EsploraJoystickMouse/EsploraJoystickMouse.ino b/libraries/Esplora/examples/Beginners/EsploraJoystickMouse/EsploraJoystickMouse.ino index 8d9260e3c41..9324fb5bc73 100644 --- a/libraries/Esplora/examples/Beginners/EsploraJoystickMouse/EsploraJoystickMouse.ino +++ b/libraries/Esplora/examples/Beginners/EsploraJoystickMouse/EsploraJoystickMouse.ino @@ -1,9 +1,9 @@ /* Esplora Joystick Mouse - + This sketch shows you how to read the joystick and use it to control the movement of the cursor on your computer. You're making your Esplora into a mouse! - + WARNING: this sketch will take over your mouse movement. If you lose control of your mouse do the following: 1) unplug the Esplora. @@ -11,13 +11,17 @@ 3) hold the reset button down while plugging your Esplora back in 4) while holding reset, click "Upload" 5) when you see the message "Done compiling", release the reset button. - + This will stop your Esplora from controlling your mouse while you upload a sketch that doesn't take control of the mouse. - + Created on 22 Dec 2012 by Tom Igoe + Updated 8 March 2014 + by Scott Fitzgerald + http://arduino.cc/en/Reference/EsploraReadJoystickSwitch + This example is in the public domain. */ @@ -27,7 +31,7 @@ void setup() { Serial.begin(9600); // initialize serial communication with your computer Mouse.begin(); // take control of the mouse -} +} void loop() { @@ -41,10 +45,16 @@ void loop() Serial.print("\tButton: "); // print a tab character and a label for the button Serial.print(button); // print the button value - int mouseX = map( xValue,-512, 512, 10, -10); // map the X value to a range of movement for the mouse X - int mouseY = map( yValue,-512, 512, -10, 10); // map the Y value to a range of movement for the mouse Y + int mouseX = map(xValue, -512, 512, 10, -10); // map the X value to a range of movement for the mouse X + int mouseY = map(yValue, -512, 512, -10, 10); // map the Y value to a range of movement for the mouse Y Mouse.move(mouseX, mouseY, 0); // move the mouse - + + if (button == 0) { // if the joystick button is pressed + Mouse.press(); // send a mouse click + } else { + Mouse.release(); // if it's not pressed, release the mouse button + } + delay(10); // a short delay before moving again } diff --git a/libraries/Esplora/keywords.txt b/libraries/Esplora/keywords.txt index b225991f605..18d394b3199 100644 --- a/libraries/Esplora/keywords.txt +++ b/libraries/Esplora/keywords.txt @@ -28,6 +28,9 @@ writeBlue KEYWORD2 readRed KEYWORD2 readGreen KEYWORD2 readBlue KEYWORD2 +readTinkerkitInput KEYWORD2 +readTinkerkitInputA KEYWORD2 +readTinkerkitInputB KEYWORD2 tone KEYWORD2 noTone KEYWORD2 diff --git a/libraries/Ethernet/EthernetClient.cpp b/libraries/Ethernet/EthernetClient.cpp index 9885efb7850..ef3d19b8b41 100644 --- a/libraries/Ethernet/EthernetClient.cpp +++ b/libraries/Ethernet/EthernetClient.cpp @@ -163,3 +163,7 @@ uint8_t EthernetClient::status() { EthernetClient::operator bool() { return _sock != MAX_SOCK_NUM; } + +bool EthernetClient::operator==(const EthernetClient& rhs) { + return _sock == rhs._sock && _sock != MAX_SOCK_NUM && rhs._sock != MAX_SOCK_NUM; +} diff --git a/libraries/Ethernet/EthernetClient.h b/libraries/Ethernet/EthernetClient.h index 44740fea7d0..1992db05240 100644 --- a/libraries/Ethernet/EthernetClient.h +++ b/libraries/Ethernet/EthernetClient.h @@ -24,6 +24,8 @@ class EthernetClient : public Client { virtual void stop(); virtual uint8_t connected(); virtual operator bool(); + virtual bool operator==(const EthernetClient&); + virtual bool operator!=(const EthernetClient& rhs) { return !this->operator==(rhs); }; friend class EthernetServer; diff --git a/libraries/Ethernet/examples/AdvancedChatServer/AdvancedChatServer.ino b/libraries/Ethernet/examples/AdvancedChatServer/AdvancedChatServer.ino new file mode 100644 index 00000000000..6fa2787e0dd --- /dev/null +++ b/libraries/Ethernet/examples/AdvancedChatServer/AdvancedChatServer.ino @@ -0,0 +1,108 @@ +/* + Advanced Chat Server + + A more advanced server that distributes any incoming messages + to all connected clients but the client the message comes from. + To use telnet to your device's IP address and type. + You can see the client's input in the serial monitor as well. + Using an Arduino Wiznet Ethernet shield. + + Circuit: + * Ethernet shield attached to pins 10, 11, 12, 13 + * Analog inputs attached to pins A0 through A5 (optional) + + created 18 Dec 2009 + by David A. Mellis + modified 9 Apr 2012 + by Tom Igoe + redesigned to make use of operator== 25 Nov 2013 + by Norbert Truchsess + + */ + +#include +#include + +// Enter a MAC address and IP address for your controller below. +// The IP address will be dependent on your local network. +// gateway and subnet are optional: +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +IPAddress ip(192,168,1, 177); +IPAddress gateway(192,168,1, 1); +IPAddress subnet(255, 255, 0, 0); + + +// telnet defaults to port 23 +EthernetServer server(23); + +EthernetClient clients[4]; + +void setup() { + // initialize the ethernet device + Ethernet.begin(mac, ip, gateway, subnet); + // start listening for clients + server.begin(); + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for Leonardo only + } + + + Serial.print("Chat server address:"); + Serial.println(Ethernet.localIP()); +} + +void loop() { + // wait for a new client: + EthernetClient client = server.available(); + + // when the client sends the first byte, say hello: + if (client) { + + boolean newClient = true; + for (byte i=0;i<4;i++) { + //check whether this client refers to the same socket as one of the existing instances: + if (clients[i]==client) { + newClient = false; + break; + } + } + + if (newClient) { + //check which of the existing clients can be overridden: + for (byte i=0;i<4;i++) { + if (!clients[i] && clients[i]!=client) { + clients[i] = client; + // clead out the input buffer: + client.flush(); + Serial.println("We have a new client"); + client.print("Hello, client number: "); + client.print(i); + client.println(); + break; + } + } + } + + if (client.available() > 0) { + // read the bytes incoming from the client: + char thisChar = client.read(); + // echo the bytes back to all other connected clients: + for (byte i=0;i<4;i++) { + if (clients[i] && (clients[i]!=client)) { + clients[i].write(thisChar); + } + } + // echo the bytes to the server as well: + Serial.write(thisChar); + } + } + for (byte i=0;i<4;i++) { + if (!(clients[i].connected())) { + // client.stop() invalidates the internal socket-descriptor, so next use of == will allways return false; + clients[i].stop(); + } + } +} diff --git a/libraries/Ethernet/examples/TwitterClient/TwitterClient.ino b/libraries/Ethernet/examples/TwitterClient/TwitterClient.ino deleted file mode 100644 index 9fee1feab3c..00000000000 --- a/libraries/Ethernet/examples/TwitterClient/TwitterClient.ino +++ /dev/null @@ -1,136 +0,0 @@ -/* - Twitter Client with Strings - - This sketch connects to Twitter using an Ethernet shield. It parses the XML - returned, and looks for this is a tweet - - You can use the Arduino Ethernet shield, or the Adafruit Ethernet shield, - either one will work, as long as it's got a Wiznet Ethernet module on board. - - This example uses the DHCP routines in the Ethernet library which is part of the - Arduino core from version 1.0 beta 1 - - This example uses the String library, which is part of the Arduino core from - version 0019. - - Circuit: - * Ethernet shield attached to pins 10, 11, 12, 13 - - created 21 May 2011 - modified 9 Apr 2012 - by Tom Igoe - - This code is in the public domain. - - */ -#include -#include - - -// Enter a MAC address and IP address for your controller below. -// The IP address will be dependent on your local network: -byte mac[] = { - 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x01 }; -IPAddress ip(192,168,1,20); - -// initialize the library instance: -EthernetClient client; - -const unsigned long requestInterval = 60000; // delay between requests - -char serverName[] = "api.twitter.com"; // twitter URL - -boolean requested; // whether you've made a request since connecting -unsigned long lastAttemptTime = 0; // last time you connected to the server, in milliseconds - -String currentLine = ""; // string to hold the text from server -String tweet = ""; // string to hold the tweet -boolean readingTweet = false; // if you're currently reading the tweet - -void setup() { - // reserve space for the strings: - currentLine.reserve(256); - tweet.reserve(150); - - // Open serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - - // attempt a DHCP connection: - Serial.println("Attempting to get an IP address using DHCP:"); - if (!Ethernet.begin(mac)) { - // if DHCP fails, start with a hard-coded address: - Serial.println("failed to get an IP address using DHCP, trying manually"); - Ethernet.begin(mac, ip); - } - Serial.print("My address:"); - Serial.println(Ethernet.localIP()); - // connect to Twitter: - connectToServer(); -} - - - -void loop() -{ - if (client.connected()) { - if (client.available()) { - // read incoming bytes: - char inChar = client.read(); - - // add incoming byte to end of line: - currentLine += inChar; - - // if you get a newline, clear the line: - if (inChar == '\n') { - currentLine = ""; - } - // if the current line ends with , it will - // be followed by the tweet: - if ( currentLine.endsWith("")) { - // tweet is beginning. Clear the tweet string: - readingTweet = true; - tweet = ""; - } - // if you're currently reading the bytes of a tweet, - // add them to the tweet String: - if (readingTweet) { - if (inChar != '<') { - tweet += inChar; - } - else { - // if you got a "<" character, - // you've reached the end of the tweet: - readingTweet = false; - Serial.println(tweet); - // close the connection to the server: - client.stop(); - } - } - } - } - else if (millis() - lastAttemptTime > requestInterval) { - // if you're not connected, and two minutes have passed since - // your last connection, then attempt to connect again: - connectToServer(); - } -} - -void connectToServer() { - // attempt to connect, and wait a millisecond: - Serial.println("connecting to server..."); - if (client.connect(serverName, 80)) { - Serial.println("making HTTP request..."); - // make HTTP GET request to twitter: - client.println("GET /1/statuses/user_timeline.xml?screen_name=arduino&count=1 HTTP/1.1"); - client.println("HOST: api.twitter.com"); - client.println("Connection: close"); - client.println(); - } - // note the time of this connect attempt: - lastAttemptTime = millis(); -} - diff --git a/libraries/Ethernet/examples/WebServer/WebServer.ino b/libraries/Ethernet/examples/WebServer/WebServer.ino index 0573f059d5e..689eb7d393d 100644 --- a/libraries/Ethernet/examples/WebServer/WebServer.ino +++ b/libraries/Ethernet/examples/WebServer/WebServer.ino @@ -22,7 +22,7 @@ // The IP address will be dependent on your local network: byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; -IPAddress ip(192,168,1, 177); +IPAddress ip(192,168,1,177); // Initialize the Ethernet server library // with the IP address and port you want to use @@ -63,12 +63,11 @@ void loop() { // send a standard http response header client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); - client.println("Connection: close"); + client.println("Connection: close"); // the connection will be closed after completion of the response + client.println("Refresh: 5"); // refresh the page automatically every 5 sec client.println(); client.println(""); client.println(""); - // add a meta refresh tag, so the browser pulls again every 5 seconds: - client.println(""); // output the value of each analog input pin for (int analogChannel = 0; analogChannel < 6; analogChannel++) { int sensorReading = analogRead(analogChannel); @@ -95,7 +94,7 @@ void loop() { delay(1); // close the connection: client.stop(); - Serial.println("client disonnected"); + Serial.println("client disconnected"); } } diff --git a/libraries/Ethernet/examples/PachubeClient/PachubeClient.ino b/libraries/Ethernet/examples/XivelyClient/XivelyClient.ino similarity index 90% rename from libraries/Ethernet/examples/PachubeClient/PachubeClient.ino rename to libraries/Ethernet/examples/XivelyClient/XivelyClient.ino index dfd2d40106a..23ae72fec11 100644 --- a/libraries/Ethernet/examples/PachubeClient/PachubeClient.ino +++ b/libraries/Ethernet/examples/XivelyClient/XivelyClient.ino @@ -1,12 +1,12 @@ /* - Pachube sensor client + Xively sensor client - This sketch connects an analog sensor to Pachube (http://www.pachube.com) + This sketch connects an analog sensor to Xively (http://www.xively.com) using a Wiznet Ethernet shield. You can use the Arduino Ethernet shield, or the Adafruit Ethernet shield, either one will work, as long as it's got a Wiznet Ethernet module on board. - This example has been updated to use version 2.0 of the Pachube.com API. + This example has been updated to use version 2.0 of the Xively.com API. To make it work, create a feed with a datastream, and give it the ID sensor1. Or change the code below to match your feed. @@ -19,7 +19,7 @@ modified 9 Apr 2012 by Tom Igoe with input from Usman Haque and Joe Saavedra -http://arduino.cc/en/Tutorial/PachubeClient +http://arduino.cc/en/Tutorial/XivelyClient This code is in the public domain. */ @@ -27,7 +27,7 @@ http://arduino.cc/en/Tutorial/PachubeClient #include #include -#define APIKEY "YOUR API KEY GOES HERE" // replace your pachube api key here +#define APIKEY "YOUR API KEY GOES HERE" // replace your xively api key here #define FEEDID 00000 // replace your feed ID #define USERAGENT "My Project" // user agent is the project name @@ -45,12 +45,12 @@ EthernetClient client; // if you don't want to use DNS (and reduce your sketch size) // use the numeric IP instead of the name for the server: -IPAddress server(216,52,233,122); // numeric IP for api.pachube.com -//char server[] = "api.pachube.com"; // name address for pachube API +IPAddress server(216,52,233,122); // numeric IP for api.xively.com +//char server[] = "api.xively.com"; // name address for xively API unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds boolean lastConnected = false; // state of the connection last time through the main loop -const unsigned long postingInterval = 10*1000; //delay between updates to Pachube.com +const unsigned long postingInterval = 10*1000; //delay between updates to Xively.com void setup() { // Open serial communications and wait for port to open: @@ -107,8 +107,8 @@ void sendData(int thisData) { client.print("PUT /v2/feeds/"); client.print(FEEDID); client.println(".csv HTTP/1.1"); - client.println("Host: api.pachube.com"); - client.print("X-PachubeApiKey: "); + client.println("Host: api.xively.com"); + client.print("X-XivelyApiKey: "); client.println(APIKEY); client.print("User-Agent: "); client.println(USERAGENT); diff --git a/libraries/Ethernet/examples/PachubeClientString/PachubeClientString.ino b/libraries/Ethernet/examples/XivelyClientString/XivelyClientString.ino similarity index 88% rename from libraries/Ethernet/examples/PachubeClientString/PachubeClientString.ino rename to libraries/Ethernet/examples/XivelyClientString/XivelyClientString.ino index 26472d12f75..4df79b70635 100644 --- a/libraries/Ethernet/examples/PachubeClientString/PachubeClientString.ino +++ b/libraries/Ethernet/examples/XivelyClientString/XivelyClientString.ino @@ -1,12 +1,12 @@ /* - Pachube sensor client with Strings + Xively sensor client with Strings - This sketch connects an analog sensor to Pachube (http://www.pachube.com) + This sketch connects an analog sensor to Xively (http://www.xively.com) using a Wiznet Ethernet shield. You can use the Arduino Ethernet shield, or the Adafruit Ethernet shield, either one will work, as long as it's got a Wiznet Ethernet module on board. - This example has been updated to use version 2.0 of the pachube.com API. + This example has been updated to use version 2.0 of the xively.com API. To make it work, create a feed with two datastreams, and give them the IDs sensor1 and sensor2. Or change the code below to match your feed. @@ -23,7 +23,7 @@ modified 8 September 2012 by Scott Fitzgerald - http://arduino.cc/en/Tutorial/PachubeClientString + http://arduino.cc/en/Tutorial/XivelyClientString This code is in the public domain. */ @@ -32,7 +32,7 @@ #include -#define APIKEY "YOUR API KEY GOES HERE" // replace your Pachube api key here +#define APIKEY "YOUR API KEY GOES HERE" // replace your Xively api key here #define FEEDID 00000 // replace your feed ID #define USERAGENT "My Project" // user agent is the project name @@ -51,12 +51,12 @@ EthernetClient client; // if you don't want to use DNS (and reduce your sketch size) // use the numeric IP instead of the name for the server: -IPAddress server(216,52,233,121); // numeric IP for api.pachube.com -//char server[] = "api.pachube.com"; // name address for pachube API +IPAddress server(216,52,233,121); // numeric IP for api.xively.com +//char server[] = "api.xively.com"; // name address for xively API unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds boolean lastConnected = false; // state of the connection last time through the main loop -const unsigned long postingInterval = 10*1000; //delay between updates to pachube.com +const unsigned long postingInterval = 10*1000; //delay between updates to xively.com void setup() { // Open serial communications and wait for port to open: @@ -85,7 +85,7 @@ void loop() { dataString += sensorReading; // you can append multiple readings to this String if your - // pachube feed is set up to handle multiple values: + // xively feed is set up to handle multiple values: int otherSensorReading = analogRead(A1); dataString += "\nsensor2,"; dataString += otherSensorReading; @@ -125,8 +125,8 @@ void sendData(String thisData) { client.print("PUT /v2/feeds/"); client.print(FEEDID); client.println(".csv HTTP/1.1"); - client.println("Host: api.pachube.com"); - client.print("X-pachubeApiKey: "); + client.println("Host: api.xively.com"); + client.print("X-xivelyApiKey: "); client.println(APIKEY); client.print("User-Agent: "); client.println(USERAGENT); diff --git a/libraries/GSM/examples/GSMPachubeClient/GSMPachubeClient.ino b/libraries/GSM/examples/GSMXivelyClient/GSMXivelyClient.ino similarity index 90% rename from libraries/GSM/examples/GSMPachubeClient/GSMPachubeClient.ino rename to libraries/GSM/examples/GSMXivelyClient/GSMXivelyClient.ino index 2885c9bba25..4253c814b8e 100644 --- a/libraries/GSM/examples/GSMPachubeClient/GSMPachubeClient.ino +++ b/libraries/GSM/examples/GSMXivelyClient/GSMXivelyClient.ino @@ -1,10 +1,10 @@ /* - GSM Pachube client + GSM Xively client - This sketch connects an analog sensor to Pachube (http://www.pachube.com) + This sketch connects an analog sensor to Xively (http://www.xively.com) using a Telefonica GSM/GPRS shield. - This example has been updated to use version 2.0 of the Pachube.com API. + This example has been updated to use version 2.0 of the Xively.com API. To make it work, create a feed with a datastream, and give it the ID sensor1. Or change the code below to match your feed. @@ -19,15 +19,15 @@ This code is in the public domain. - http://arduino.cc/en/Tutorial/GSMExamplesPachubeClient + http://arduino.cc/en/Tutorial/GSMExamplesXivelyClient */ // libraries #include -// Pachube Client data -#define APIKEY "YOUR API KEY GOES HERE" // replace your pachube api key here +// Xively Client data +#define APIKEY "YOUR API KEY GOES HERE" // replace your xively api key here #define FEEDID 00000 // replace your feed ID #define USERAGENT "My Project" // user agent is the project name @@ -46,12 +46,12 @@ GSM gsmAccess; // if you don't want to use DNS (and reduce your sketch size) // use the numeric IP instead of the name for the server: -// IPAddress server(216,52,233,121); // numeric IP for api.pachube.com -char server[] = "api.pachube.com"; // name address for pachube API +// IPAddress server(216,52,233,121); // numeric IP for api.xively.com +char server[] = "api.xively.com"; // name address for xively API unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds boolean lastConnected = false; // state of the connection last time through the main loop -const unsigned long postingInterval = 10*1000; //delay between updates to Pachube.com +const unsigned long postingInterval = 10*1000; //delay between updates to Xively.com void setup() { @@ -126,7 +126,7 @@ void sendData(int thisData) client.print("PUT /v2/feeds/"); client.print(FEEDID); client.println(".csv HTTP/1.1"); - client.println("Host: api.pachube.com"); + client.println("Host: api.xively.com"); client.print("X-ApiKey: "); client.println(APIKEY); client.print("User-Agent: "); diff --git a/libraries/GSM/examples/GSMPachubeClientString/GSMPachubeClientString.ino b/libraries/GSM/examples/GSMXivelyClientString/GSMXivelyClientString.ino similarity index 89% rename from libraries/GSM/examples/GSMPachubeClientString/GSMPachubeClientString.ino rename to libraries/GSM/examples/GSMXivelyClientString/GSMXivelyClientString.ino index 9f6ea531d67..d07b3ffdf8b 100644 --- a/libraries/GSM/examples/GSMPachubeClientString/GSMPachubeClientString.ino +++ b/libraries/GSM/examples/GSMXivelyClientString/GSMXivelyClientString.ino @@ -1,10 +1,10 @@ /* - Pachube client with Strings + Xively client with Strings - This sketch connects two analog sensors to Pachube (http://www.pachube.com) + This sketch connects two analog sensors to Xively (http://www.xively.com) through a Telefonica GSM/GPRS shield. - This example has been updated to use version 2.0 of the Pachube.com API. + This example has been updated to use version 2.0 of the Xively.com API. To make it work, create a feed with two datastreams, and give them the IDs sensor1 and sensor2. Or change the code below to match your feed. @@ -27,8 +27,8 @@ // Include the GSM library #include -// Pachube login information -#define APIKEY "YOUR API KEY GOES HERE" // replace your pachube api key here +// Xively login information +#define APIKEY "YOUR API KEY GOES HERE" // replace your xively api key here #define FEEDID 00000 // replace your feed ID #define USERAGENT "My Project" // user agent is the project name @@ -47,12 +47,12 @@ GSM gsmAccess; // if you don't want to use DNS (and reduce your sketch size) // use the numeric IP instead of the name for the server: -// IPAddress server(216,52,233,121); // numeric IP for api.pachube.com -char server[] = "api.pachube.com"; // name address for Pachube API +// IPAddress server(216,52,233,121); // numeric IP for api.xively.com +char server[] = "api.xively.com"; // name address for Xively API unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds boolean lastConnected = false; // state of the connection last time through the main loop -const unsigned long postingInterval = 10*1000; // delay between updates to Pachube.com +const unsigned long postingInterval = 10*1000; // delay between updates to Xively.com void setup() { @@ -92,7 +92,7 @@ void loop() dataString += sensorReading; // you can append multiple readings to this String to - // send the pachube feed multiple values + // send the xively feed multiple values int otherSensorReading = analogRead(A1); dataString += "\nsensor2,"; dataString += otherSensorReading; @@ -138,7 +138,7 @@ void sendData(String thisData) client.print("PUT /v2/feeds/"); client.print(FEEDID); client.println(".csv HTTP/1.1"); - client.println("Host: api.pachube.com"); + client.println("Host: api.xively.com"); client.print("X-ApiKey: "); client.println(APIKEY); client.print("User-Agent: "); diff --git a/libraries/GSM/examples/GsmTwitterClient/GsmTwitterClient.ino b/libraries/GSM/examples/GsmTwitterClient/GsmTwitterClient.ino deleted file mode 100644 index 30321417eed..00000000000 --- a/libraries/GSM/examples/GsmTwitterClient/GsmTwitterClient.ino +++ /dev/null @@ -1,162 +0,0 @@ -/* - GSM Twitter Client with Strings - - This sketch connects to Twitter using an Arduino GSM shield. - It parses the XML returned, and looks for the string this is a tweet - - This example uses the String library, which is part of the Arduino core from - version 0019. - - Circuit: - * GSM shield attached to an Arduino - * SIM card with a data plan - - created 8 Mar 2012 - by Tom Igoe - - http://arduino.cc/en/Tutorial/GSMExamplesTwitterClient - - This code is in the public domain. - - */ - -// libraries -#include - -// PIN Number -#define PINNUMBER "" - -// APN data -#define GPRS_APN "APN" // replace your GPRS APN -#define GPRS_LOGIN "LOGIN" // replace with your GPRS login -#define GPRS_PASSWORD "PASSWORD" // replace with your GPRS password - -// initialize the library instance -GSMClient client; -GPRS gprs; -GSM gsmAccess; - -const unsigned long requestInterval = 30*1000; // delay between requests: 30 seconds - -// API Twitter URL -char server[] = "api.twitter.com"; - -boolean requested; // whether you've made a request since connecting -unsigned long lastAttemptTime = 0; // last time you connected to the server, in milliseconds - -String currentLine = ""; // string to hold the text from server -String tweet = ""; // string to hold the tweet -boolean readingTweet = false; // if you're currently reading the tweet - -void setup() -{ - // reserve space for the strings: - currentLine.reserve(256); - tweet.reserve(150); - - // initialize serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - // connection state - boolean notConnected = true; - - // After starting the modem with GSM.begin() - // attach the shield to the GPRS network with the APN, login and password - while(notConnected) - { - if((gsmAccess.begin(PINNUMBER)==GSM_READY) & - (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY)) - notConnected = false; - else - { - Serial.println("Not connected"); - delay(1000); - } - } - - Serial.println("Connected to GPRS network"); - - Serial.println("connecting..."); - connectToServer(); -} - - - -void loop() -{ - char c; - if (client.connected()) - { - if (client.available()) - { - // read incoming bytes: - char inChar = client.read(); - - // add incoming byte to end of line: - currentLine += inChar; - - // if you get a newline, clear the line: - if (inChar == '\n') - { - currentLine = ""; - } - - // if the current line ends with , it will - // be followed by the tweet: - if (currentLine.endsWith("")) - { - // tweet is beginning. Clear the tweet string: - readingTweet = true; - tweet = ""; - } - - // if you're currently reading the bytes of a tweet, - // add them to the tweet String: - if (readingTweet) - { - if (inChar != '<') - { - tweet += inChar; - } - else - { - // if you got a "<" character, - // you've reached the end of the tweet: - readingTweet = false; - Serial.println(tweet); - - // close the connection to the server: - client.stop(); - } - } - } - } - else if (millis() - lastAttemptTime > requestInterval) - { - // if you're not connected, and two minutes have passed since - // your last connection, then attempt to connect again: - connectToServer(); - } -} - -/* - Connect to API Twitter server and do a request for timeline -*/ -void connectToServer() -{ - // attempt to connect, and wait a millisecond: - Serial.println("connecting to server..."); - if (client.connect(server, 80)) - { - Serial.println("making HTTP request..."); - // make HTTP GET request to twitter: - client.println("GET /1/statuses/user_timeline.xml?screen_name=arduino&count=1 HTTP/1.1"); - client.println("HOST: api.twitter.com"); - client.println(); - } - // note the time of this connect attempt: - lastAttemptTime = millis(); -} diff --git a/libraries/LiquidCrystal/examples/CustomCharacter/CustomCharacter.ino b/libraries/LiquidCrystal/examples/CustomCharacter/CustomCharacter.ino index d3ce479246d..f714a3a44de 100644 --- a/libraries/LiquidCrystal/examples/CustomCharacter/CustomCharacter.ino +++ b/libraries/LiquidCrystal/examples/CustomCharacter/CustomCharacter.ino @@ -22,8 +22,11 @@ * wiper to LCD VO pin (pin 3) * 10K poterntiometer on pin A0 - created21 Mar 2011 + created 21 Mar 2011 by Tom Igoe + modified 11 Nov 2013 + by Scott Fitzgerald + Based on Adafruit's example at https://github.com/adafruit/SPI_VFD/blob/master/examples/createChar/createChar.pde @@ -96,7 +99,11 @@ byte armsUp[8] = { 0b00100, 0b01010 }; + void setup() { + // initialize LCD and set up the number of columns and rows: + lcd.begin(16, 2); + // create a new character lcd.createChar(0, heart); // create a new character @@ -108,11 +115,9 @@ void setup() { // create a new character lcd.createChar(4, armsUp); - // set up the lcd's number of columns and rows: - lcd.begin(16, 2); // Print a message to the lcd. lcd.print("I "); - lcd.write(0); + lcd.write(byte(0)); // when calling lcd.write() '0' must be cast as a byte lcd.print(" Arduino! "); lcd.write(1); @@ -133,6 +138,3 @@ void loop() { lcd.write(4); delay(delayTime); } - - - diff --git a/libraries/RobotIRremote/IRremote.cpp b/libraries/RobotIRremote/IRremote.cpp new file mode 100644 index 00000000000..fb76cb64db9 --- /dev/null +++ b/libraries/RobotIRremote/IRremote.cpp @@ -0,0 +1,777 @@ +/* + * IRremote + * Version 0.11 August, 2009 + * Copyright 2009 Ken Shirriff + * For details, see http://arcfn.com/2009/08/multi-protocol-infrared-remote-library.html + * + * Modified by Paul Stoffregen to support other boards and timers + * Modified by Mitra Ardron + * Added Sanyo and Mitsubishi controllers + * Modified Sony to spot the repeat codes that some Sony's send + * + * Interrupt code based on NECIRrcv by Joe Knapp + * http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1210243556 + * Also influenced by http://zovirl.com/2008/11/12/building-a-universal-remote-with-an-arduino/ + * + * JVC and Panasonic protocol added by Kristian Lauszus (Thanks to zenwheel and other people at the original blog post) + */ + +#include "IRremote.h" +#include "IRremoteInt.h" + +// Provides ISR +#include + +volatile irparams_t irparams; + +// These versions of MATCH, MATCH_MARK, and MATCH_SPACE are only for debugging. +// To use them, set DEBUG in IRremoteInt.h +// Normally macros are used for efficiency +#ifdef DEBUG +int MATCH(int measured, int desired) { + Serial.print("Testing: "); + Serial.print(TICKS_LOW(desired), DEC); + Serial.print(" <= "); + Serial.print(measured, DEC); + Serial.print(" <= "); + Serial.println(TICKS_HIGH(desired), DEC); + return measured >= TICKS_LOW(desired) && measured <= TICKS_HIGH(desired); +} + +int MATCH_MARK(int measured_ticks, int desired_us) { + Serial.print("Testing mark "); + Serial.print(measured_ticks * USECPERTICK, DEC); + Serial.print(" vs "); + Serial.print(desired_us, DEC); + Serial.print(": "); + Serial.print(TICKS_LOW(desired_us + MARK_EXCESS), DEC); + Serial.print(" <= "); + Serial.print(measured_ticks, DEC); + Serial.print(" <= "); + Serial.println(TICKS_HIGH(desired_us + MARK_EXCESS), DEC); + return measured_ticks >= TICKS_LOW(desired_us + MARK_EXCESS) && measured_ticks <= TICKS_HIGH(desired_us + MARK_EXCESS); +} + +int MATCH_SPACE(int measured_ticks, int desired_us) { + Serial.print("Testing space "); + Serial.print(measured_ticks * USECPERTICK, DEC); + Serial.print(" vs "); + Serial.print(desired_us, DEC); + Serial.print(": "); + Serial.print(TICKS_LOW(desired_us - MARK_EXCESS), DEC); + Serial.print(" <= "); + Serial.print(measured_ticks, DEC); + Serial.print(" <= "); + Serial.println(TICKS_HIGH(desired_us - MARK_EXCESS), DEC); + return measured_ticks >= TICKS_LOW(desired_us - MARK_EXCESS) && measured_ticks <= TICKS_HIGH(desired_us - MARK_EXCESS); +} +#else +int MATCH(int measured, int desired) {return measured >= TICKS_LOW(desired) && measured <= TICKS_HIGH(desired);} +int MATCH_MARK(int measured_ticks, int desired_us) {return MATCH(measured_ticks, (desired_us + MARK_EXCESS));} +int MATCH_SPACE(int measured_ticks, int desired_us) {return MATCH(measured_ticks, (desired_us - MARK_EXCESS));} +#endif + +IRrecv::IRrecv(int recvpin) +{ + irparams.recvpin = recvpin; + irparams.blinkflag = 0; +} + +// initialization +void IRrecv::enableIRIn() { + cli(); + // setup pulse clock timer interrupt + //Prescale /8 (16M/8 = 0.5 microseconds per tick) + // Therefore, the timer interval can range from 0.5 to 128 microseconds + // depending on the reset value (255 to 0) + TIMER_CONFIG_NORMAL(); + + //Timer2 Overflow Interrupt Enable + TIMER_ENABLE_INTR; + + TIMER_RESET; + + sei(); // enable interrupts + + // initialize state machine variables + irparams.rcvstate = STATE_IDLE; + irparams.rawlen = 0; + + // set pin modes + pinMode(irparams.recvpin, INPUT); +} + +// enable/disable blinking of pin 13 on IR processing +void IRrecv::blink13(int blinkflag) +{ + irparams.blinkflag = blinkflag; + if (blinkflag) + pinMode(BLINKLED, OUTPUT); +} + +// TIMER2 interrupt code to collect raw data. +// Widths of alternating SPACE, MARK are recorded in rawbuf. +// Recorded in ticks of 50 microseconds. +// rawlen counts the number of entries recorded so far. +// First entry is the SPACE between transmissions. +// As soon as a SPACE gets long, ready is set, state switches to IDLE, timing of SPACE continues. +// As soon as first MARK arrives, gap width is recorded, ready is cleared, and new logging starts +ISR(TIMER_INTR_NAME) +{ + TIMER_RESET; + + uint8_t irdata = (uint8_t)digitalRead(irparams.recvpin); + + irparams.timer++; // One more 50us tick + if (irparams.rawlen >= RAWBUF) { + // Buffer overflow + irparams.rcvstate = STATE_STOP; + } + switch(irparams.rcvstate) { + case STATE_IDLE: // In the middle of a gap + if (irdata == MARK) { + if (irparams.timer < GAP_TICKS) { + // Not big enough to be a gap. + irparams.timer = 0; + } + else { + // gap just ended, record duration and start recording transmission + irparams.rawlen = 0; + irparams.rawbuf[irparams.rawlen++] = irparams.timer; + irparams.timer = 0; + irparams.rcvstate = STATE_MARK; + } + } + break; + case STATE_MARK: // timing MARK + if (irdata == SPACE) { // MARK ended, record time + irparams.rawbuf[irparams.rawlen++] = irparams.timer; + irparams.timer = 0; + irparams.rcvstate = STATE_SPACE; + } + break; + case STATE_SPACE: // timing SPACE + if (irdata == MARK) { // SPACE just ended, record it + irparams.rawbuf[irparams.rawlen++] = irparams.timer; + irparams.timer = 0; + irparams.rcvstate = STATE_MARK; + } + else { // SPACE + if (irparams.timer > GAP_TICKS) { + // big SPACE, indicates gap between codes + // Mark current code as ready for processing + // Switch to STOP + // Don't reset timer; keep counting space width + irparams.rcvstate = STATE_STOP; + } + } + break; + case STATE_STOP: // waiting, measuring gap + if (irdata == MARK) { // reset gap timer + irparams.timer = 0; + } + break; + } + + if (irparams.blinkflag) { + if (irdata == MARK) { + BLINKLED_ON(); // turn pin 13 LED on + } + else { + BLINKLED_OFF(); // turn pin 13 LED off + } + } +} + +void IRrecv::resume() { + irparams.rcvstate = STATE_IDLE; + irparams.rawlen = 0; +} + + + +// Decodes the received IR message +// Returns 0 if no data ready, 1 if data ready. +// Results of decoding are stored in results +int IRrecv::decode(decode_results *results) { + results->rawbuf = irparams.rawbuf; + results->rawlen = irparams.rawlen; + if (irparams.rcvstate != STATE_STOP) { + return ERR; + } + +#ifdef DEBUG + Serial.println("Attempting NEC decode"); +#endif + if (decodeNEC(results)) { + return DECODED; + } +/* +#ifdef DEBUG + Serial.println("Attempting Sony decode"); +#endif + if (decodeSony(results)) { + return DECODED; + }*/ +/* +#ifdef DEBUG + Serial.println("Attempting Sanyo decode"); +#endif + if (decodeSanyo(results)) { + return DECODED; + } + */ +/* +#ifdef DEBUG + Serial.println("Attempting Mitsubishi decode"); +#endif + if (decodeMitsubishi(results)) { + return DECODED; + }*/ +/* +#ifdef DEBUG + Serial.println("Attempting RC5 decode"); +#endif + if (decodeRC5(results)) { + return DECODED; + } + */ +/* +#ifdef DEBUG + Serial.println("Attempting RC6 decode"); +#endif + if (decodeRC6(results)) { + return DECODED; + } + */ +/* +#ifdef DEBUG + Serial.println("Attempting Panasonic decode"); +#endif + if (decodePanasonic(results)) { + return DECODED; + } + */ +/* +#ifdef DEBUG + Serial.println("Attempting JVC decode"); +#endif + if (decodeJVC(results)) { + return DECODED; + }*/ + // decodeHash returns a hash on any input. + // Thus, it needs to be last in the list. + // If you add any decodes, add them before this. + if (decodeHash(results)) { + return DECODED; + } + // Throw away and start over + resume(); + return ERR; +} + + +// NECs have a repeat only 4 items long +long IRrecv::decodeNEC(decode_results *results) { + long data = 0; + int offset = 1; // Skip first space + // Initial mark + if (!MATCH_MARK(results->rawbuf[offset], NEC_HDR_MARK)) { + return ERR; + } + offset++; + // Check for repeat + if (irparams.rawlen == 4 && + MATCH_SPACE(results->rawbuf[offset], NEC_RPT_SPACE) && + MATCH_MARK(results->rawbuf[offset+1], NEC_BIT_MARK)) { + results->bits = 0; + results->value = REPEAT; + results->decode_type = NEC; + return DECODED; + } + if (irparams.rawlen < 2 * NEC_BITS + 4) { + return ERR; + } + // Initial space + if (!MATCH_SPACE(results->rawbuf[offset], NEC_HDR_SPACE)) { + return ERR; + } + offset++; + for (int i = 0; i < NEC_BITS; i++) { + if (!MATCH_MARK(results->rawbuf[offset], NEC_BIT_MARK)) { + return ERR; + } + offset++; + if (MATCH_SPACE(results->rawbuf[offset], NEC_ONE_SPACE)) { + data = (data << 1) | 1; + } + else if (MATCH_SPACE(results->rawbuf[offset], NEC_ZERO_SPACE)) { + data <<= 1; + } + else { + return ERR; + } + offset++; + } + // Success + results->bits = NEC_BITS; + results->value = data; + results->decode_type = NEC; + return DECODED; +} +/* +long IRrecv::decodeSony(decode_results *results) { + long data = 0; + if (irparams.rawlen < 2 * SONY_BITS + 2) { + return ERR; + } + int offset = 0; // Dont skip first space, check its size + + // Some Sony's deliver repeats fast after first + // unfortunately can't spot difference from of repeat from two fast clicks + if (results->rawbuf[offset] < SONY_DOUBLE_SPACE_USECS) { + // Serial.print("IR Gap found: "); + results->bits = 0; + results->value = REPEAT; + results->decode_type = SANYO; + return DECODED; + } + offset++; + + // Initial mark + if (!MATCH_MARK(results->rawbuf[offset], SONY_HDR_MARK)) { + return ERR; + } + offset++; + + while (offset + 1 < irparams.rawlen) { + if (!MATCH_SPACE(results->rawbuf[offset], SONY_HDR_SPACE)) { + break; + } + offset++; + if (MATCH_MARK(results->rawbuf[offset], SONY_ONE_MARK)) { + data = (data << 1) | 1; + } + else if (MATCH_MARK(results->rawbuf[offset], SONY_ZERO_MARK)) { + data <<= 1; + } + else { + return ERR; + } + offset++; + } + + // Success + results->bits = (offset - 1) / 2; + if (results->bits < 12) { + results->bits = 0; + return ERR; + } + results->value = data; + results->decode_type = SONY; + return DECODED; +}*/ + +/* +// I think this is a Sanyo decoder - serial = SA 8650B +// Looks like Sony except for timings, 48 chars of data and time/space different +long IRrecv::decodeSanyo(decode_results *results) { + long data = 0; + if (irparams.rawlen < 2 * SANYO_BITS + 2) { + return ERR; + } + int offset = 0; // Skip first space + // Initial space + // Put this back in for debugging - note can't use #DEBUG as if Debug on we don't see the repeat cos of the delay + //Serial.print("IR Gap: "); + //Serial.println( results->rawbuf[offset]); + //Serial.println( "test against:"); + //Serial.println(results->rawbuf[offset]); + + if (results->rawbuf[offset] < SANYO_DOUBLE_SPACE_USECS) { + // Serial.print("IR Gap found: "); + results->bits = 0; + results->value = REPEAT; + results->decode_type = SANYO; + return DECODED; + } + offset++; + + // Initial mark + if (!MATCH_MARK(results->rawbuf[offset], SANYO_HDR_MARK)) { + return ERR; + } + offset++; + + // Skip Second Mark + if (!MATCH_MARK(results->rawbuf[offset], SANYO_HDR_MARK)) { + return ERR; + } + offset++; + + while (offset + 1 < irparams.rawlen) { + if (!MATCH_SPACE(results->rawbuf[offset], SANYO_HDR_SPACE)) { + break; + } + offset++; + if (MATCH_MARK(results->rawbuf[offset], SANYO_ONE_MARK)) { + data = (data << 1) | 1; + } + else if (MATCH_MARK(results->rawbuf[offset], SANYO_ZERO_MARK)) { + data <<= 1; + } + else { + return ERR; + } + offset++; + } + + // Success + results->bits = (offset - 1) / 2; + if (results->bits < 12) { + results->bits = 0; + return ERR; + } + results->value = data; + results->decode_type = SANYO; + return DECODED; +} +*/ +/* +// Looks like Sony except for timings, 48 chars of data and time/space different +long IRrecv::decodeMitsubishi(decode_results *results) { + // Serial.print("?!? decoding Mitsubishi:");Serial.print(irparams.rawlen); Serial.print(" want "); Serial.println( 2 * MITSUBISHI_BITS + 2); + long data = 0; + if (irparams.rawlen < 2 * MITSUBISHI_BITS + 2) { + return ERR; + } + int offset = 0; // Skip first space + // Initial space + // Put this back in for debugging - note can't use #DEBUG as if Debug on we don't see the repeat cos of the delay + //Serial.print("IR Gap: "); + //Serial.println( results->rawbuf[offset]); + //Serial.println( "test against:"); + //Serial.println(results->rawbuf[offset]); + + // Not seeing double keys from Mitsubishi + //if (results->rawbuf[offset] < MITSUBISHI_DOUBLE_SPACE_USECS) { + // Serial.print("IR Gap found: "); + // results->bits = 0; + // results->value = REPEAT; + // results->decode_type = MITSUBISHI; + // return DECODED; + //} + + offset++; + + // Typical + // 14200 7 41 7 42 7 42 7 17 7 17 7 18 7 41 7 18 7 17 7 17 7 18 7 41 8 17 7 17 7 18 7 17 7 + + // Initial Space + if (!MATCH_MARK(results->rawbuf[offset], MITSUBISHI_HDR_SPACE)) { + return ERR; + } + offset++; + while (offset + 1 < irparams.rawlen) { + if (MATCH_MARK(results->rawbuf[offset], MITSUBISHI_ONE_MARK)) { + data = (data << 1) | 1; + } + else if (MATCH_MARK(results->rawbuf[offset], MITSUBISHI_ZERO_MARK)) { + data <<= 1; + } + else { + // Serial.println("A"); Serial.println(offset); Serial.println(results->rawbuf[offset]); + return ERR; + } + offset++; + if (!MATCH_SPACE(results->rawbuf[offset], MITSUBISHI_HDR_SPACE)) { + // Serial.println("B"); Serial.println(offset); Serial.println(results->rawbuf[offset]); + break; + } + offset++; + } + + // Success + results->bits = (offset - 1) / 2; + if (results->bits < MITSUBISHI_BITS) { + results->bits = 0; + return ERR; + } + results->value = data; + results->decode_type = MITSUBISHI; + return DECODED; +}*/ + + +// Gets one undecoded level at a time from the raw buffer. +// The RC5/6 decoding is easier if the data is broken into time intervals. +// E.g. if the buffer has MARK for 2 time intervals and SPACE for 1, +// successive calls to getRClevel will return MARK, MARK, SPACE. +// offset and used are updated to keep track of the current position. +// t1 is the time interval for a single bit in microseconds. +// Returns -1 for error (measured time interval is not a multiple of t1). +int IRrecv::getRClevel(decode_results *results, int *offset, int *used, int t1) { + if (*offset >= results->rawlen) { + // After end of recorded buffer, assume SPACE. + return SPACE; + } + int width = results->rawbuf[*offset]; + int val = ((*offset) % 2) ? MARK : SPACE; + int correction = (val == MARK) ? MARK_EXCESS : - MARK_EXCESS; + + int avail; + if (MATCH(width, t1 + correction)) { + avail = 1; + } + else if (MATCH(width, 2*t1 + correction)) { + avail = 2; + } + else if (MATCH(width, 3*t1 + correction)) { + avail = 3; + } + else { + return -1; + } + + (*used)++; + if (*used >= avail) { + *used = 0; + (*offset)++; + } +#ifdef DEBUG + if (val == MARK) { + Serial.println("MARK"); + } + else { + Serial.println("SPACE"); + } +#endif + return val; +} +/* +long IRrecv::decodeRC5(decode_results *results) { + if (irparams.rawlen < MIN_RC5_SAMPLES + 2) { + return ERR; + } + int offset = 1; // Skip gap space + long data = 0; + int used = 0; + // Get start bits + if (getRClevel(results, &offset, &used, RC5_T1) != MARK) return ERR; + if (getRClevel(results, &offset, &used, RC5_T1) != SPACE) return ERR; + if (getRClevel(results, &offset, &used, RC5_T1) != MARK) return ERR; + int nbits; + for (nbits = 0; offset < irparams.rawlen; nbits++) { + int levelA = getRClevel(results, &offset, &used, RC5_T1); + int levelB = getRClevel(results, &offset, &used, RC5_T1); + if (levelA == SPACE && levelB == MARK) { + // 1 bit + data = (data << 1) | 1; + } + else if (levelA == MARK && levelB == SPACE) { + // zero bit + data <<= 1; + } + else { + return ERR; + } + } + + // Success + results->bits = nbits; + results->value = data; + results->decode_type = RC5; + return DECODED; +}*/ +/* +long IRrecv::decodeRC6(decode_results *results) { + if (results->rawlen < MIN_RC6_SAMPLES) { + return ERR; + } + int offset = 1; // Skip first space + // Initial mark + if (!MATCH_MARK(results->rawbuf[offset], RC6_HDR_MARK)) { + return ERR; + } + offset++; + if (!MATCH_SPACE(results->rawbuf[offset], RC6_HDR_SPACE)) { + return ERR; + } + offset++; + long data = 0; + int used = 0; + // Get start bit (1) + if (getRClevel(results, &offset, &used, RC6_T1) != MARK) return ERR; + if (getRClevel(results, &offset, &used, RC6_T1) != SPACE) return ERR; + int nbits; + for (nbits = 0; offset < results->rawlen; nbits++) { + int levelA, levelB; // Next two levels + levelA = getRClevel(results, &offset, &used, RC6_T1); + if (nbits == 3) { + // T bit is double wide; make sure second half matches + if (levelA != getRClevel(results, &offset, &used, RC6_T1)) return ERR; + } + levelB = getRClevel(results, &offset, &used, RC6_T1); + if (nbits == 3) { + // T bit is double wide; make sure second half matches + if (levelB != getRClevel(results, &offset, &used, RC6_T1)) return ERR; + } + if (levelA == MARK && levelB == SPACE) { // reversed compared to RC5 + // 1 bit + data = (data << 1) | 1; + } + else if (levelA == SPACE && levelB == MARK) { + // zero bit + data <<= 1; + } + else { + return ERR; // Error + } + } + // Success + results->bits = nbits; + results->value = data; + results->decode_type = RC6; + return DECODED; +}*/ +/* +long IRrecv::decodePanasonic(decode_results *results) { + unsigned long long data = 0; + int offset = 1; + + if (!MATCH_MARK(results->rawbuf[offset], PANASONIC_HDR_MARK)) { + return ERR; + } + offset++; + if (!MATCH_MARK(results->rawbuf[offset], PANASONIC_HDR_SPACE)) { + return ERR; + } + offset++; + + // decode address + for (int i = 0; i < PANASONIC_BITS; i++) { + if (!MATCH_MARK(results->rawbuf[offset++], PANASONIC_BIT_MARK)) { + return ERR; + } + if (MATCH_SPACE(results->rawbuf[offset],PANASONIC_ONE_SPACE)) { + data = (data << 1) | 1; + } else if (MATCH_SPACE(results->rawbuf[offset],PANASONIC_ZERO_SPACE)) { + data <<= 1; + } else { + return ERR; + } + offset++; + } + results->value = (unsigned long)data; + results->panasonicAddress = (unsigned int)(data >> 32); + results->decode_type = PANASONIC; + results->bits = PANASONIC_BITS; + return DECODED; +}*/ +/* +long IRrecv::decodeJVC(decode_results *results) { + long data = 0; + int offset = 1; // Skip first space + // Check for repeat + if (irparams.rawlen - 1 == 33 && + MATCH_MARK(results->rawbuf[offset], JVC_BIT_MARK) && + MATCH_MARK(results->rawbuf[irparams.rawlen-1], JVC_BIT_MARK)) { + results->bits = 0; + results->value = REPEAT; + results->decode_type = JVC; + return DECODED; + } + // Initial mark + if (!MATCH_MARK(results->rawbuf[offset], JVC_HDR_MARK)) { + return ERR; + } + offset++; + if (irparams.rawlen < 2 * JVC_BITS + 1 ) { + return ERR; + } + // Initial space + if (!MATCH_SPACE(results->rawbuf[offset], JVC_HDR_SPACE)) { + return ERR; + } + offset++; + for (int i = 0; i < JVC_BITS; i++) { + if (!MATCH_MARK(results->rawbuf[offset], JVC_BIT_MARK)) { + return ERR; + } + offset++; + if (MATCH_SPACE(results->rawbuf[offset], JVC_ONE_SPACE)) { + data = (data << 1) | 1; + } + else if (MATCH_SPACE(results->rawbuf[offset], JVC_ZERO_SPACE)) { + data <<= 1; + } + else { + return ERR; + } + offset++; + } + //Stop bit + if (!MATCH_MARK(results->rawbuf[offset], JVC_BIT_MARK)){ + return ERR; + } + // Success + results->bits = JVC_BITS; + results->value = data; + results->decode_type = JVC; + return DECODED; +}*/ + +/* ----------------------------------------------------------------------- + * hashdecode - decode an arbitrary IR code. + * Instead of decoding using a standard encoding scheme + * (e.g. Sony, NEC, RC5), the code is hashed to a 32-bit value. + * + * The algorithm: look at the sequence of MARK signals, and see if each one + * is shorter (0), the same length (1), or longer (2) than the previous. + * Do the same with the SPACE signals. Hszh the resulting sequence of 0's, + * 1's, and 2's to a 32-bit value. This will give a unique value for each + * different code (probably), for most code systems. + * + * http://arcfn.com/2010/01/using-arbitrary-remotes-with-arduino.html + */ + +// Compare two tick values, returning 0 if newval is shorter, +// 1 if newval is equal, and 2 if newval is longer +// Use a tolerance of 20% +int IRrecv::compare(unsigned int oldval, unsigned int newval) { + if (newval < oldval * .8) { + return 0; + } + else if (oldval < newval * .8) { + return 2; + } + else { + return 1; + } +} + +// Use FNV hash algorithm: http://isthe.com/chongo/tech/comp/fnv/#FNV-param +#define FNV_PRIME_32 16777619 +#define FNV_BASIS_32 2166136261 + +/* Converts the raw code values into a 32-bit hash code. + * Hopefully this code is unique for each button. + * This isn't a "real" decoding, just an arbitrary value. + */ +long IRrecv::decodeHash(decode_results *results) { + // Require at least 6 samples to prevent triggering on noise + if (results->rawlen < 6) { + return ERR; + } + long hash = FNV_BASIS_32; + for (int i = 1; i+2 < results->rawlen; i++) { + int value = compare(results->rawbuf[i], results->rawbuf[i+2]); + // Add value into the hash + hash = (hash * FNV_PRIME_32) ^ value; + } + results->value = hash; + results->bits = 32; + results->decode_type = UNKNOWN; + return DECODED; +} + diff --git a/libraries/RobotIRremote/IRremote.h b/libraries/RobotIRremote/IRremote.h new file mode 100644 index 00000000000..56dc349b658 --- /dev/null +++ b/libraries/RobotIRremote/IRremote.h @@ -0,0 +1,94 @@ +/* + * IRremote + * Version 0.1 July, 2009 + * Copyright 2009 Ken Shirriff + * For details, see http://arcfn.com/2009/08/multi-protocol-infrared-remote-library.htm http://arcfn.com + * Edited by Mitra to add new controller SANYO + * + * Interrupt code based on NECIRrcv by Joe Knapp + * http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1210243556 + * Also influenced by http://zovirl.com/2008/11/12/building-a-universal-remote-with-an-arduino/ + * + * JVC and Panasonic protocol added by Kristian Lauszus (Thanks to zenwheel and other people at the original blog post) + */ + +#ifndef IRremote_h +#define IRremote_h + +// The following are compile-time library options. +// If you change them, recompile the library. +// If DEBUG is defined, a lot of debugging output will be printed during decoding. +// TEST must be defined for the IRtest unittests to work. It will make some +// methods virtual, which will be slightly slower, which is why it is optional. +// #define DEBUG +// #define TEST + +// Results returned from the decoder +class decode_results { +public: + int decode_type; // NEC, SONY, RC5, UNKNOWN + unsigned int panasonicAddress; // This is only used for decoding Panasonic data + unsigned long value; // Decoded value + int bits; // Number of bits in decoded value + volatile unsigned int *rawbuf; // Raw intervals in .5 us ticks + int rawlen; // Number of records in rawbuf. +}; + +// Values for decode_type +#define NEC 1 +#define SONY 2 +#define RC5 3 +#define RC6 4 +#define DISH 5 +#define SHARP 6 +#define PANASONIC 7 +#define JVC 8 +#define SANYO 9 +#define MITSUBISHI 10 +#define UNKNOWN -1 + +// Decoded value for NEC when a repeat code is received +#define REPEAT 0xffffffff + +// main class for receiving IR +class IRrecv +{ +public: + IRrecv(int recvpin); + void blink13(int blinkflag); + int decode(decode_results *results); + void enableIRIn(); + void resume(); +private: + // These are called by decode + int getRClevel(decode_results *results, int *offset, int *used, int t1); + long decodeNEC(decode_results *results); + //long decodeSony(decode_results *results); + //long decodeSanyo(decode_results *results); + //long decodeMitsubishi(decode_results *results); + //long decodeRC5(decode_results *results); + //long decodeRC6(decode_results *results); + //long decodePanasonic(decode_results *results); + //long decodeJVC(decode_results *results); + long decodeHash(decode_results *results); + int compare(unsigned int oldval, unsigned int newval); + +} +; + +// Only used for testing; can remove virtual for shorter code +#ifdef TEST +#define VIRTUAL virtual +#else +#define VIRTUAL +#endif +// Some useful constants + +#define USECPERTICK 50 // microseconds per clock interrupt tick +#define RAWBUF 100 // Length of raw duration buffer + +// Marks tend to be 100us too long, and spaces 100us too short +// when received due to sensor lag. +#define MARK_EXCESS 100 + +#endif diff --git a/libraries/RobotIRremote/IRremoteInt.h b/libraries/RobotIRremote/IRremoteInt.h new file mode 100644 index 00000000000..0efdbddd397 --- /dev/null +++ b/libraries/RobotIRremote/IRremoteInt.h @@ -0,0 +1,446 @@ +/* + * IRremote + * Version 0.1 July, 2009 + * Copyright 2009 Ken Shirriff + * For details, see http://arcfn.com/2009/08/multi-protocol-infrared-remote-library.html + * + * Modified by Paul Stoffregen to support other boards and timers + * + * Interrupt code based on NECIRrcv by Joe Knapp + * http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1210243556 + * Also influenced by http://zovirl.com/2008/11/12/building-a-universal-remote-with-an-arduino/ + * + * JVC and Panasonic protocol added by Kristian Lauszus (Thanks to zenwheel and other people at the original blog post) + */ + +#ifndef IRremoteint_h +#define IRremoteint_h + +#if defined(ARDUINO) && ARDUINO >= 100 +#include +#else +#include +#endif + +// define which timer to use +// +// Uncomment the timer you wish to use on your board. If you +// are using another library which uses timer2, you have options +// to switch IRremote to use a different timer. + +// Arduino Mega +#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) + //#define IR_USE_TIMER1 // tx = pin 11 + #define IR_USE_TIMER2 // tx = pin 9 + //#define IR_USE_TIMER3 // tx = pin 5 + //#define IR_USE_TIMER4 // tx = pin 6 + //#define IR_USE_TIMER5 // tx = pin 46 + +// Teensy 1.0 +#elif defined(__AVR_AT90USB162__) + #define IR_USE_TIMER1 // tx = pin 17 + +// Teensy 2.0 +#elif defined(__AVR_ATmega32U4__) + //#define IR_USE_TIMER1 // tx = pin 14 + //#define IR_USE_TIMER3 // tx = pin 9 + #define IR_USE_TIMER4_HS // tx = pin 10 + +// Teensy++ 1.0 & 2.0 +#elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__) + //#define IR_USE_TIMER1 // tx = pin 25 + #define IR_USE_TIMER2 // tx = pin 1 + //#define IR_USE_TIMER3 // tx = pin 16 + +// Sanguino +#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__) + //#define IR_USE_TIMER1 // tx = pin 13 + #define IR_USE_TIMER2 // tx = pin 14 + +// Atmega8 +#elif defined(__AVR_ATmega8P__) || defined(__AVR_ATmega8__) + #define IR_USE_TIMER1 // tx = pin 9 + +// Arduino Duemilanove, Diecimila, LilyPad, Mini, Fio, etc +#else + //#define IR_USE_TIMER1 // tx = pin 9 + #define IR_USE_TIMER2 // tx = pin 3 +#endif + + + +#ifdef F_CPU +#define SYSCLOCK F_CPU // main Arduino clock +#else +#define SYSCLOCK 16000000 // main Arduino clock +#endif + +#define ERR 0 +#define DECODED 1 + + +// defines for setting and clearing register bits +#ifndef cbi +#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit)) +#endif +#ifndef sbi +#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit)) +#endif + +// Pulse parms are *50-100 for the Mark and *50+100 for the space +// First MARK is the one after the long gap +// pulse parameters in usec +#define NEC_HDR_MARK 9000 +#define NEC_HDR_SPACE 4500 +#define NEC_BIT_MARK 560 +#define NEC_ONE_SPACE 1600 +#define NEC_ZERO_SPACE 560 +#define NEC_RPT_SPACE 2250 + +#define SONY_HDR_MARK 2400 +#define SONY_HDR_SPACE 600 +#define SONY_ONE_MARK 1200 +#define SONY_ZERO_MARK 600 +#define SONY_RPT_LENGTH 45000 +#define SONY_DOUBLE_SPACE_USECS 500 // usually ssee 713 - not using ticks as get number wrapround + +// SA 8650B +#define SANYO_HDR_MARK 3500 // seen range 3500 +#define SANYO_HDR_SPACE 950 // seen 950 +#define SANYO_ONE_MARK 2400 // seen 2400 +#define SANYO_ZERO_MARK 700 // seen 700 +#define SANYO_DOUBLE_SPACE_USECS 800 // usually ssee 713 - not using ticks as get number wrapround +#define SANYO_RPT_LENGTH 45000 + +// Mitsubishi RM 75501 +// 14200 7 41 7 42 7 42 7 17 7 17 7 18 7 41 7 18 7 17 7 17 7 18 7 41 8 17 7 17 7 18 7 17 7 + +// #define MITSUBISHI_HDR_MARK 250 // seen range 3500 +#define MITSUBISHI_HDR_SPACE 350 // 7*50+100 +#define MITSUBISHI_ONE_MARK 1950 // 41*50-100 +#define MITSUBISHI_ZERO_MARK 750 // 17*50-100 +// #define MITSUBISHI_DOUBLE_SPACE_USECS 800 // usually ssee 713 - not using ticks as get number wrapround +// #define MITSUBISHI_RPT_LENGTH 45000 + + +#define RC5_T1 889 +#define RC5_RPT_LENGTH 46000 + +#define RC6_HDR_MARK 2666 +#define RC6_HDR_SPACE 889 +#define RC6_T1 444 +#define RC6_RPT_LENGTH 46000 + +#define SHARP_BIT_MARK 245 +#define SHARP_ONE_SPACE 1805 +#define SHARP_ZERO_SPACE 795 +#define SHARP_GAP 600000 +#define SHARP_TOGGLE_MASK 0x3FF +#define SHARP_RPT_SPACE 3000 + +#define DISH_HDR_MARK 400 +#define DISH_HDR_SPACE 6100 +#define DISH_BIT_MARK 400 +#define DISH_ONE_SPACE 1700 +#define DISH_ZERO_SPACE 2800 +#define DISH_RPT_SPACE 6200 +#define DISH_TOP_BIT 0x8000 + +#define PANASONIC_HDR_MARK 3502 +#define PANASONIC_HDR_SPACE 1750 +#define PANASONIC_BIT_MARK 502 +#define PANASONIC_ONE_SPACE 1244 +#define PANASONIC_ZERO_SPACE 400 + +#define JVC_HDR_MARK 8000 +#define JVC_HDR_SPACE 4000 +#define JVC_BIT_MARK 600 +#define JVC_ONE_SPACE 1600 +#define JVC_ZERO_SPACE 550 +#define JVC_RPT_LENGTH 60000 + +#define SHARP_BITS 15 +#define DISH_BITS 16 + +#define TOLERANCE 25 // percent tolerance in measurements +#define LTOL (1.0 - TOLERANCE/100.) +#define UTOL (1.0 + TOLERANCE/100.) + +#define _GAP 5000 // Minimum map between transmissions +#define GAP_TICKS (_GAP/USECPERTICK) + +#define TICKS_LOW(us) (int) (((us)*LTOL/USECPERTICK)) +#define TICKS_HIGH(us) (int) (((us)*UTOL/USECPERTICK + 1)) + +// receiver states +#define STATE_IDLE 2 +#define STATE_MARK 3 +#define STATE_SPACE 4 +#define STATE_STOP 5 + +// information for the interrupt handler +typedef struct { + uint8_t recvpin; // pin for IR data from detector + uint8_t rcvstate; // state machine + uint8_t blinkflag; // TRUE to enable blinking of pin 13 on IR processing + unsigned int timer; // state timer, counts 50uS ticks. + unsigned int rawbuf[RAWBUF]; // raw data + uint8_t rawlen; // counter of entries in rawbuf +} +irparams_t; + +// Defined in IRremote.cpp +extern volatile irparams_t irparams; + +// IR detector output is active low +#define MARK 0 +#define SPACE 1 + +#define TOPBIT 0x80000000 + +#define NEC_BITS 32 +#define SONY_BITS 12 +#define SANYO_BITS 12 +#define MITSUBISHI_BITS 16 +#define MIN_RC5_SAMPLES 11 +#define MIN_RC6_SAMPLES 1 +#define PANASONIC_BITS 48 +#define JVC_BITS 16 + + + + +// defines for timer2 (8 bits) +#if defined(IR_USE_TIMER2) +#define TIMER_RESET +#define TIMER_ENABLE_PWM (TCCR2A |= _BV(COM2B1)) +#define TIMER_DISABLE_PWM (TCCR2A &= ~(_BV(COM2B1))) +#define TIMER_ENABLE_INTR (TIMSK2 = _BV(OCIE2A)) +#define TIMER_DISABLE_INTR (TIMSK2 = 0) +#define TIMER_INTR_NAME TIMER2_COMPA_vect +#define TIMER_CONFIG_KHZ(val) ({ \ + const uint8_t pwmval = SYSCLOCK / 2000 / (val); \ + TCCR2A = _BV(WGM20); \ + TCCR2B = _BV(WGM22) | _BV(CS20); \ + OCR2A = pwmval; \ + OCR2B = pwmval / 3; \ +}) +#define TIMER_COUNT_TOP (SYSCLOCK * USECPERTICK / 1000000) +#if (TIMER_COUNT_TOP < 256) +#define TIMER_CONFIG_NORMAL() ({ \ + TCCR2A = _BV(WGM21); \ + TCCR2B = _BV(CS20); \ + OCR2A = TIMER_COUNT_TOP; \ + TCNT2 = 0; \ +}) +#else +#define TIMER_CONFIG_NORMAL() ({ \ + TCCR2A = _BV(WGM21); \ + TCCR2B = _BV(CS21); \ + OCR2A = TIMER_COUNT_TOP / 8; \ + TCNT2 = 0; \ +}) +#endif +#if defined(CORE_OC2B_PIN) +#define TIMER_PWM_PIN CORE_OC2B_PIN /* Teensy */ +#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) +#define TIMER_PWM_PIN 9 /* Arduino Mega */ +#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__) +#define TIMER_PWM_PIN 14 /* Sanguino */ +#else +#define TIMER_PWM_PIN 3 /* Arduino Duemilanove, Diecimila, LilyPad, etc */ +#endif + + +// defines for timer1 (16 bits) +#elif defined(IR_USE_TIMER1) +#define TIMER_RESET +#define TIMER_ENABLE_PWM (TCCR1A |= _BV(COM1A1)) +#define TIMER_DISABLE_PWM (TCCR1A &= ~(_BV(COM1A1))) +#if defined(__AVR_ATmega8P__) || defined(__AVR_ATmega8__) + #define TIMER_ENABLE_INTR (TIMSK = _BV(OCIE1A)) + #define TIMER_DISABLE_INTR (TIMSK = 0) +#else + #define TIMER_ENABLE_INTR (TIMSK1 = _BV(OCIE1A)) + #define TIMER_DISABLE_INTR (TIMSK1 = 0) +#endif +#define TIMER_INTR_NAME TIMER1_COMPA_vect +#define TIMER_CONFIG_KHZ(val) ({ \ + const uint16_t pwmval = SYSCLOCK / 2000 / (val); \ + TCCR1A = _BV(WGM11); \ + TCCR1B = _BV(WGM13) | _BV(CS10); \ + ICR1 = pwmval; \ + OCR1A = pwmval / 3; \ +}) +#define TIMER_CONFIG_NORMAL() ({ \ + TCCR1A = 0; \ + TCCR1B = _BV(WGM12) | _BV(CS10); \ + OCR1A = SYSCLOCK * USECPERTICK / 1000000; \ + TCNT1 = 0; \ +}) +#if defined(CORE_OC1A_PIN) +#define TIMER_PWM_PIN CORE_OC1A_PIN /* Teensy */ +#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) +#define TIMER_PWM_PIN 11 /* Arduino Mega */ +#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__) +#define TIMER_PWM_PIN 13 /* Sanguino */ +#else +#define TIMER_PWM_PIN 9 /* Arduino Duemilanove, Diecimila, LilyPad, etc */ +#endif + + +// defines for timer3 (16 bits) +#elif defined(IR_USE_TIMER3) +#define TIMER_RESET +#define TIMER_ENABLE_PWM (TCCR3A |= _BV(COM3A1)) +#define TIMER_DISABLE_PWM (TCCR3A &= ~(_BV(COM3A1))) +#define TIMER_ENABLE_INTR (TIMSK3 = _BV(OCIE3A)) +#define TIMER_DISABLE_INTR (TIMSK3 = 0) +#define TIMER_INTR_NAME TIMER3_COMPA_vect +#define TIMER_CONFIG_KHZ(val) ({ \ + const uint16_t pwmval = SYSCLOCK / 2000 / (val); \ + TCCR3A = _BV(WGM31); \ + TCCR3B = _BV(WGM33) | _BV(CS30); \ + ICR3 = pwmval; \ + OCR3A = pwmval / 3; \ +}) +#define TIMER_CONFIG_NORMAL() ({ \ + TCCR3A = 0; \ + TCCR3B = _BV(WGM32) | _BV(CS30); \ + OCR3A = SYSCLOCK * USECPERTICK / 1000000; \ + TCNT3 = 0; \ +}) +#if defined(CORE_OC3A_PIN) +#define TIMER_PWM_PIN CORE_OC3A_PIN /* Teensy */ +#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) +#define TIMER_PWM_PIN 5 /* Arduino Mega */ +#else +#error "Please add OC3A pin number here\n" +#endif + + +// defines for timer4 (10 bits, high speed option) +#elif defined(IR_USE_TIMER4_HS) +#define TIMER_RESET +#define TIMER_ENABLE_PWM (TCCR4A |= _BV(COM4A1)) +#define TIMER_DISABLE_PWM (TCCR4A &= ~(_BV(COM4A1))) +#define TIMER_ENABLE_INTR (TIMSK4 = _BV(TOIE4)) +#define TIMER_DISABLE_INTR (TIMSK4 = 0) +#define TIMER_INTR_NAME TIMER4_OVF_vect +#define TIMER_CONFIG_KHZ(val) ({ \ + const uint16_t pwmval = SYSCLOCK / 2000 / (val); \ + TCCR4A = (1<> 8; \ + OCR4C = pwmval; \ + TC4H = (pwmval / 3) >> 8; \ + OCR4A = (pwmval / 3) & 255; \ +}) +#define TIMER_CONFIG_NORMAL() ({ \ + TCCR4A = 0; \ + TCCR4B = _BV(CS40); \ + TCCR4C = 0; \ + TCCR4D = 0; \ + TCCR4E = 0; \ + TC4H = (SYSCLOCK * USECPERTICK / 1000000) >> 8; \ + OCR4C = (SYSCLOCK * USECPERTICK / 1000000) & 255; \ + TC4H = 0; \ + TCNT4 = 0; \ +}) +#if defined(CORE_OC4A_PIN) +#define TIMER_PWM_PIN CORE_OC4A_PIN /* Teensy */ +#elif defined(__AVR_ATmega32U4__) +#define TIMER_PWM_PIN 13 /* Leonardo */ +#else +#error "Please add OC4A pin number here\n" +#endif + + +// defines for timer4 (16 bits) +#elif defined(IR_USE_TIMER4) +#define TIMER_RESET +#define TIMER_ENABLE_PWM (TCCR4A |= _BV(COM4A1)) +#define TIMER_DISABLE_PWM (TCCR4A &= ~(_BV(COM4A1))) +#define TIMER_ENABLE_INTR (TIMSK4 = _BV(OCIE4A)) +#define TIMER_DISABLE_INTR (TIMSK4 = 0) +#define TIMER_INTR_NAME TIMER4_COMPA_vect +#define TIMER_CONFIG_KHZ(val) ({ \ + const uint16_t pwmval = SYSCLOCK / 2000 / (val); \ + TCCR4A = _BV(WGM41); \ + TCCR4B = _BV(WGM43) | _BV(CS40); \ + ICR4 = pwmval; \ + OCR4A = pwmval / 3; \ +}) +#define TIMER_CONFIG_NORMAL() ({ \ + TCCR4A = 0; \ + TCCR4B = _BV(WGM42) | _BV(CS40); \ + OCR4A = SYSCLOCK * USECPERTICK / 1000000; \ + TCNT4 = 0; \ +}) +#if defined(CORE_OC4A_PIN) +#define TIMER_PWM_PIN CORE_OC4A_PIN +#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) +#define TIMER_PWM_PIN 6 /* Arduino Mega */ +#else +#error "Please add OC4A pin number here\n" +#endif + + +// defines for timer5 (16 bits) +#elif defined(IR_USE_TIMER5) +#define TIMER_RESET +#define TIMER_ENABLE_PWM (TCCR5A |= _BV(COM5A1)) +#define TIMER_DISABLE_PWM (TCCR5A &= ~(_BV(COM5A1))) +#define TIMER_ENABLE_INTR (TIMSK5 = _BV(OCIE5A)) +#define TIMER_DISABLE_INTR (TIMSK5 = 0) +#define TIMER_INTR_NAME TIMER5_COMPA_vect +#define TIMER_CONFIG_KHZ(val) ({ \ + const uint16_t pwmval = SYSCLOCK / 2000 / (val); \ + TCCR5A = _BV(WGM51); \ + TCCR5B = _BV(WGM53) | _BV(CS50); \ + ICR5 = pwmval; \ + OCR5A = pwmval / 3; \ +}) +#define TIMER_CONFIG_NORMAL() ({ \ + TCCR5A = 0; \ + TCCR5B = _BV(WGM52) | _BV(CS50); \ + OCR5A = SYSCLOCK * USECPERTICK / 1000000; \ + TCNT5 = 0; \ +}) +#if defined(CORE_OC5A_PIN) +#define TIMER_PWM_PIN CORE_OC5A_PIN +#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) +#define TIMER_PWM_PIN 46 /* Arduino Mega */ +#else +#error "Please add OC5A pin number here\n" +#endif + + +#else // unknown timer +#error "Internal code configuration error, no known IR_USE_TIMER# defined\n" +#endif + + +// defines for blinking the LED +#if defined(CORE_LED0_PIN) +#define BLINKLED CORE_LED0_PIN +#define BLINKLED_ON() (digitalWrite(CORE_LED0_PIN, HIGH)) +#define BLINKLED_OFF() (digitalWrite(CORE_LED0_PIN, LOW)) +#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) +#define BLINKLED 13 +#define BLINKLED_ON() (PORTB |= B10000000) +#define BLINKLED_OFF() (PORTB &= B01111111) +#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__) +#define BLINKLED 0 +#define BLINKLED_ON() (PORTD |= B00000001) +#define BLINKLED_OFF() (PORTD &= B11111110) +#else +#define BLINKLED 13 +#define BLINKLED_ON() (PORTB |= B00100000) +#define BLINKLED_OFF() (PORTB &= B11011111) +#endif + +#endif diff --git a/libraries/RobotIRremote/IRremoteTools.cpp b/libraries/RobotIRremote/IRremoteTools.cpp new file mode 100644 index 00000000000..4cd6d569e6c --- /dev/null +++ b/libraries/RobotIRremote/IRremoteTools.cpp @@ -0,0 +1,23 @@ +#include "IRremote.h" +#include "IRremoteTools.h" +#include + +int RECV_PIN = TKD2; // the pin the IR receiver is connected to +IRrecv irrecv(RECV_PIN); // an instance of the IR receiver object +decode_results results; // container for received IR codes + +void beginIRremote(){ + irrecv.enableIRIn(); // Start the receiver +} + +bool IRrecived(){ + return irrecv.decode(&results); +} + +void resumeIRremote(){ + irrecv.resume(); // resume receiver +} + +unsigned long getIRresult(){ + return results.value; +} \ No newline at end of file diff --git a/libraries/RobotIRremote/IRremoteTools.h b/libraries/RobotIRremote/IRremoteTools.h new file mode 100644 index 00000000000..a61d4edfa48 --- /dev/null +++ b/libraries/RobotIRremote/IRremoteTools.h @@ -0,0 +1,12 @@ +#ifndef IRREMOTETOOLS_H +#define IRREMOTETOOLS_H + +extern void beginIRremote(); + +extern bool IRrecived(); + +extern void resumeIRremote(); + +extern unsigned long getIRresult(); + +#endif \ No newline at end of file diff --git a/build/windows/launcher/launch4j/lib/Nuvola.Icon.Theme.LICENSE.txt b/libraries/RobotIRremote/LICENSE.txt old mode 100755 new mode 100644 similarity index 90% rename from build/windows/launcher/launch4j/lib/Nuvola.Icon.Theme.LICENSE.txt rename to libraries/RobotIRremote/LICENSE.txt index cbee875ba6d..77cec6dd195 --- a/build/windows/launcher/launch4j/lib/Nuvola.Icon.Theme.LICENSE.txt +++ b/libraries/RobotIRremote/LICENSE.txt @@ -1,504 +1,458 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Libraries - - If you develop a new library, and you want it to be of the greatest -possible use to the public, we recommend making it free software that -everyone can redistribute and change. You can do so by permitting -redistribution under these terms (or, alternatively, under the terms of the -ordinary General Public License). - - To apply these terms, attach the following notices to the library. It is -safest to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least the -"copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - -Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the library, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the - library `Frob' (a library for tweaking knobs) written by James Random Hacker. - - , 1 April 1990 - Ty Coon, President of Vice - -That's all there is to it! - - + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + diff --git a/libraries/RobotIRremote/keywords.txt b/libraries/RobotIRremote/keywords.txt new file mode 100644 index 00000000000..74010c4193f --- /dev/null +++ b/libraries/RobotIRremote/keywords.txt @@ -0,0 +1,50 @@ +####################################### +# Syntax Coloring Map For IRremote +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +decode_results KEYWORD1 +IRrecv KEYWORD1 +IRsend KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +blink13 KEYWORD2 +decode KEYWORD2 +enableIRIn KEYWORD2 +resume KEYWORD2 +enableIROut KEYWORD2 +sendNEC KEYWORD2 +sendSony KEYWORD2 +sendSanyo KEYWORD2 +sendMitsubishi KEYWORD2 +sendRaw KEYWORD2 +sendRC5 KEYWORD2 +sendRC6 KEYWORD2 +sendDISH KEYWORD2 +sendSharp KEYWORD2 +sendPanasonic KEYWORD2 +sendJVC KEYWORD2 + +# +####################################### +# Constants (LITERAL1) +####################################### + +NEC LITERAL1 +SONY LITERAL1 +SANYO LITERAL1 +MITSUBISHI LITERAL1 +RC5 LITERAL1 +RC6 LITERAL1 +DISH LITERAL1 +SHARP LITERAL1 +PANASONIC LITERAL1 +JVC LITERAL1 +UNKNOWN LITERAL1 +REPEAT LITERAL1 \ No newline at end of file diff --git a/libraries/RobotIRremote/readme b/libraries/RobotIRremote/readme new file mode 100644 index 00000000000..3de652611e7 --- /dev/null +++ b/libraries/RobotIRremote/readme @@ -0,0 +1,14 @@ +This is the IRremote library for the Arduino. + +To download from github (http://github.com/shirriff/Arduino-IRremote), click on the "Downloads" link in the upper right, click "Download as zip", and get a zip file. Unzip it and rename the directory shirriff-Arduino-IRremote-nnn to IRremote + +To install, move the downloaded IRremote directory to: +arduino-1.x/libraries/IRremote +where arduino-1.x is your Arduino installation directory + +After installation you should have files such as: +arduino-1.x/libraries/IRremote/IRremote.cpp + +For details on the library see the Wiki on github or the blog post http://arcfn.com/2009/08/multi-protocol-infrared-remote-library.html + +Copyright 2009-2012 Ken Shirriff diff --git a/libraries/Robot_Control/ArduinoRobot.cpp b/libraries/Robot_Control/ArduinoRobot.cpp new file mode 100644 index 00000000000..3adac73ba8a --- /dev/null +++ b/libraries/Robot_Control/ArduinoRobot.cpp @@ -0,0 +1,40 @@ +#include "ArduinoRobot.h" +#include "Multiplexer.h" +#include "Wire.h" +#include "EasyTransfer2.h" + +//RobotControl::RobotControl(){} + +RobotControl::RobotControl():Arduino_LCD(LCD_CS,DC_LCD,RST_LCD){ + +} + +void RobotControl::begin(){ + Wire.begin(); + //Compass + //nothing here + + //TK sensors + uint8_t MuxPins[]={MUXA,MUXB,MUXC,MUXD}; + Multiplexer::begin(MuxPins,MUX_IN,4); + + //piezo + pinMode(BUZZ,OUTPUT); + + //communication + Serial1.begin(9600); + messageOut.begin(&Serial1); + messageIn.begin(&Serial1); + + //TFT initialization + //Arduino_LCD::initR(INITR_GREENTAB); +} + +void RobotControl::setMode(uint8_t mode){ + messageOut.writeByte(COMMAND_SWITCH_MODE); + messageOut.writeByte(mode); + messageOut.sendData(); +} + + +RobotControl Robot=RobotControl(); \ No newline at end of file diff --git a/libraries/Robot_Control/ArduinoRobot.h b/libraries/Robot_Control/ArduinoRobot.h new file mode 100644 index 00000000000..2b11a9484c5 --- /dev/null +++ b/libraries/Robot_Control/ArduinoRobot.h @@ -0,0 +1,374 @@ +#ifndef ArduinoRobot_h +#define ArduinoRobot_h + +#include "Arduino_LCD.h" // Hardware-specific library +//#include "FormattedText.h" +#include "SquawkSD.h" +#include "Multiplexer.h" +#include "EasyTransfer2.h" +#include "EEPROM_I2C.h" +#include "Compass.h" +#include "Fat16.h" + +#if ARDUINO >= 100 +#include "Arduino.h" +#else +#include "WProgram.h" +#endif + + +#define BUTTON_NONE -1 +#define BUTTON_LEFT 0 +#define BUTTON_DOWN 1 +#define BUTTON_UP 2 +#define BUTTON_RIGHT 3 +#define BUTTON_MIDDLE 4 +#define NUMBER_BUTTONS 5 + +//beep length +#define BEEP_SIMPLE 0 +#define BEEP_DOUBLE 1 +#define BEEP_LONG 2 + +// image locations on the EEPROM + #define HOME_BMP 0 +#define BATTERY_BMP 2048 +#define COMPASS_BMP 4096 +#define CONTROL_BMP 6144 +#define GEARS_BMP 8192 +#define LIGHT_BMP 10240 +#define OSCILLO_BMP 12288 +#define VOLT_BMP 14336 +#define INICIO_BMP 16384 // this is a full screen splash + +//Command code +#define COMMAND_SWITCH_MODE 0 +#define COMMAND_RUN 10 +#define COMMAND_MOTORS_STOP 11 +#define COMMAND_ANALOG_WRITE 20 +#define COMMAND_DIGITAL_WRITE 30 +#define COMMAND_ANALOG_READ 40 +#define COMMAND_ANALOG_READ_RE 41 +#define COMMAND_DIGITAL_READ 50 +#define COMMAND_DIGITAL_READ_RE 51 +#define COMMAND_READ_IR 60 +#define COMMAND_READ_IR_RE 61 +#define COMMAND_ACTION_DONE 70 +#define COMMAND_READ_TRIM 80 +#define COMMAND_READ_TRIM_RE 81 +#define COMMAND_PAUSE_MODE 90 +#define COMMAND_LINE_FOLLOW_CONFIG 100 + +//component codename +#define CN_LEFT_MOTOR 0 +#define CN_RIGHT_MOTOR 1 +#define CN_IR 2 + +//motor board modes +#define MODE_SIMPLE 0 +#define MODE_LINE_FOLLOW 1 +#define MODE_ADJUST_MOTOR 2 +#define MODE_IR_CONTROL 3 + +//port types, for R/W +#define TYPE_TOP_TK 0 +#define TYPE_TOP_TKD 1 +#define TYPE_BOTTOM_TK 2 + +//top TKs +#define TK0 100 +#define TK1 101 +#define TK2 102 +#define TK3 103 +#define TK4 104 +#define TK5 105 +#define TK6 106 +#define TK7 107 + +#define M0 TK0 +#define M1 TK1 +#define M2 TK2 +#define M3 TK3 +#define M4 TK4 +#define M5 TK5 +#define M6 TK6 +#define M7 TK7 + +//bottom TKs, just for communication purpose +#define B_TK1 201 +#define B_TK2 202 +#define B_TK3 203 +#define B_TK4 204 + +#define D10 B_TK1 +#define D9 B_TK2 +#define D8 B_TK4 +#define D7 B_TK3 + +//bottom IRs, for communication purpose +#define B_IR0 210 +#define B_IR1 211 +#define B_IR2 212 +#define B_IR3 213 +#define B_IR4 214 + +#ifndef LED1 +#define LED1 17 +#endif + +//320 - 337 username, +#define ADDRESS_USERNAME 320 +//338 - 355 robotname, +#define ADDRESS_ROBOTNAME 338 +//356 - 373 cityname, +#define ADDRESS_CITYNAME 356 + //374- 391 countryname, +#define ADDRESS_COUNTRYNAME 374 +//508-511 robot info +#define ADDRESS_ROBOTINFO 508 + +#define BLACK ILI9163C_BLACK +#define BLUE ILI9163C_BLUE +#define RED ILI9163C_RED +#define GREEN ILI9163C_GREEN +#define CYAN ILI9163C_CYAN +#define MAGENTA ILI9163C_MAGENTA +#define YELLOW ILI9163C_YELLOW +#define WHITE ILI9163C_WHITE + +//A data structure for storing the current state of motor board +struct MOTOR_BOARD_DATA{ + int _B_TK1; + int _B_TK2; + int _B_TK3; + int _B_TK4; + + /*int _B_IR0; + int _B_IR1; + int _B_IR2; + int _B_IR3; + int _B_IR4;*/ +}; + +/* +A message structure will be: +switch mode: + byte COMMAND_SWITCH_MODE, byte mode +run: + byte COMMAND_RUN, int speedL, int speedR +analogWrite: + byte COMMAND_ANALOG_WRITE, byte codename, byte value; +digitalWrite: + byte COMMAND_DIGITAL_WRITE, byte codename, byte value; +analogRead: + byte COMMAND_ANALOG_READ, byte codename; +analogRead return: + byte COMMAND_ANALOG_READ_RE, byte codename, int value; +digitalRead return: + byte COMMAND_DIGITAL_READ_RE, byte codename, byte value; +read IR: + byte COMMAND_READ_IR, int valueA, int valueB, int valueC, int valueD; + + +*/ +#define NUM_EEPROM_BMP 10 +struct EEPROM_BMP{ + char name[8]; + uint8_t width; + uint8_t height; + uint16_t address; +}; + +//if you call #undef USE_SQUAWK_SYNTH_SD at the beginning of your sketch, +//it's going to remove anything regarding sound playing + +class RobotControl:public Multiplexer, +public EEPROM_I2C, +public Compass, +public SquawkSynthSD, +//public FormattedText +public Arduino_LCD +{ + public: + RobotControl(); + void begin(); + void setMode(uint8_t mode); + + //Read & Write, TK0 - TK7, TKD0 - TKD1, bottom TK0 - TK4 + bool digitalRead(uint8_t port); + int analogRead(uint8_t port); + void digitalWrite(uint8_t port, bool value); + void analogWrite(uint8_t port, uint8_t value);//It's not available, as there's no pin can be used for analog write + + //IR sensors from the bottom board + //define an array as "int arr[4];", and supply the arry name here + uint16_t IRarray[5]; + void updateIR(); + + //on board Potentiometor + int knobRead(); + //Potentiometor of the motor board + int trimRead(); + + //on board piezo + void beginSpeaker(uint16_t frequency=44100); + void playMelody(char* script); + void playFile(char* filename); + void stopPlayFile(); + void beep(int beep_length=BEEP_SIMPLE); + void tempoWrite(int tempo); + void tuneWrite(float tune); + + //compass + uint16_t compassRead(); + void drawCompass(uint16_t value); + void drawBase(); + void drawDire(int16_t dire); + + //keyboard + void keyboardCalibrate(int *vals); + int8_t keyboardRead();//return the key that is being pressed?Has been pressed(with _processKeyboard)? + + //movement + void moveForward(int speed); + void moveBackward(int speed); + void turnLeft(int speed); + void turnRight(int speed); + void motorsStop(); + void motorsWritePct(int speedLeftPct, int speedRightPct); + + void motorsWrite(int speedLeft,int speedRight); + void pointTo(int degrees);//turn to an absolute angle from the compass + void turn(int degress);//turn certain degrees from the current heading + + //Line Following + void lineFollowConfig(uint8_t KP, uint8_t KD, uint8_t robotSpeed, uint8_t intergrationTime);//default 11 5 50 10 + + //TFT LCD + //use the same commands as Arduino_LCD + void beginTFT(uint16_t foreGround=BLACK, uint16_t background=WHITE); + /*void text(int value, uint8_t posX, uint8_t posY, bool EW); + void text(long value, uint8_t posX, uint8_t posY, bool EW); + void text(char* value, uint8_t posX, uint8_t posY, bool EW); + void text(char value, uint8_t posX, uint8_t posY, bool EW);*/ + void debugPrint(long value, uint8_t x=0, uint8_t y=0); + void clearScreen(); + + void drawBMP(char* filename, uint8_t x, uint8_t y);//detect if draw with EEPROM or SD, and draw it + void _drawBMP(uint32_t iconOffset, uint8_t x, uint8_t y, uint8_t width, uint8_t height);//draw from EEPROM + void _drawBMP(char* filename, uint8_t x, uint8_t y);//draw from SD + void beginBMPFromEEPROM(); + void endBMPFromEEPROM(); + + uint16_t foreGround;//foreground color + uint16_t backGround;//background color + + + //SD card + void beginSD(); + + //Information + void userNameRead(char* container); + void robotNameRead(char* container); + void cityNameRead(char* container); + void countryNameRead(char* container); + + void userNameWrite(char* text); + void robotNameWrite(char* text); + void cityNameWrite(char* text); + void countryNameWrite(char* text); + + //Others + bool isActionDone(); + void pauseMode(uint8_t onOff); + void displayLogos(); + void waitContinue(uint8_t key=BUTTON_MIDDLE); + + private: + //Read & Write + uint8_t _getTypeCode(uint8_t port);//different ports need different actions + uint8_t _portToTopMux(uint8_t port);//get the number for multiplexer within top TKs + uint8_t _topDPortToAPort(uint8_t port);//get the corrensponding analogIn pin for top TKDs + + bool _digitalReadTopMux(uint8_t port);//TK0 - TK7 + int _analogReadTopMux(uint8_t port); + + bool _digitalReadTopPin(uint8_t port); + int _analogReadTopPin(uint8_t port); + void _digitalWriteTopPin(uint8_t port, bool value); + + MOTOR_BOARD_DATA motorBoardData; + int* parseMBDPort(uint8_t port); + int get_motorBoardData(uint8_t port); + void set_motorBoardData(uint8_t port, int value); + + bool _requestDigitalRead(uint8_t port); + int _requestAnalogRead(uint8_t port); + void _requestDigitalWrite(uint8_t port, uint8_t value); + + //LCD + void _enableLCD(); + void _setWrite(uint8_t posX, uint8_t posY); + void _setErase(uint8_t posX, uint8_t posY); + + + //SD + SdCard card; + Fat16 file; + Fat16 melody; + void _enableSD(); + + //keyboard + void _processKeyboard(); //need to run in loop, detect if the key is actually pressed + int averageAnalogInput(int pinNum); + + //Ultrasonic ranger + //uint8_t pinTrigger_UR; + //uint8_t pinEcho_UR; + + //Melody + void playNote(byte period, word length, char modifier); + + //Communication + + EasyTransfer2 messageOut; + EasyTransfer2 messageIn; + + //TFT LCD + bool _isEEPROM_BMP_Allocated; + EEPROM_BMP * _eeprom_bmp; + void _drawBMP_EEPROM(uint16_t address, uint8_t width, uint8_t height); + void _drawBMP_SD(char* filename, uint8_t x, uint8_t y); + + +}; + +inline void RobotControl::userNameRead(char* container){ + EEPROM_I2C::readBuffer(ADDRESS_USERNAME,(uint8_t*)container,18); +} +inline void RobotControl::robotNameRead(char* container){ + EEPROM_I2C::readBuffer(ADDRESS_ROBOTNAME,(uint8_t*)container,18); +} +inline void RobotControl::cityNameRead(char* container){ + EEPROM_I2C::readBuffer(ADDRESS_CITYNAME,(uint8_t*)container,18); +} +inline void RobotControl::countryNameRead(char* container){ + EEPROM_I2C::readBuffer(ADDRESS_COUNTRYNAME,(uint8_t*)container,18); +} + +inline void RobotControl::userNameWrite(char* text){ + EEPROM_I2C::writePage(ADDRESS_USERNAME,(uint8_t*)text,18); +} +inline void RobotControl::robotNameWrite(char* text){ + EEPROM_I2C::writePage(ADDRESS_ROBOTNAME,(uint8_t*)text,18); +} +inline void RobotControl::cityNameWrite(char* text){ + EEPROM_I2C::writePage(ADDRESS_CITYNAME,(uint8_t*)text,18); +} +inline void RobotControl::countryNameWrite(char* text){ + EEPROM_I2C::writePage(ADDRESS_COUNTRYNAME,(uint8_t*)text,18); +} + +extern RobotControl Robot; + +#endif \ No newline at end of file diff --git a/libraries/Robot_Control/Arduino_LCD.cpp b/libraries/Robot_Control/Arduino_LCD.cpp new file mode 100644 index 00000000000..3f6aeb8639b --- /dev/null +++ b/libraries/Robot_Control/Arduino_LCD.cpp @@ -0,0 +1,707 @@ +/*************************************************** + This is a library for the Adafruit 1.8" SPI display. + This library works with the Adafruit 1.8" TFT Breakout w/SD card + ----> http://www.adafruit.com/products/358 + as well as Adafruit raw 1.8" TFT display + ----> http://www.adafruit.com/products/618 + + Check out the links above for our tutorials and wiring diagrams + These displays use SPI to communicate, 4 or 5 pins are required to + interface (RST is optional) + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing + products from Adafruit! + + Written by Limor Fried/Ladyada for Adafruit Industries. + MIT license, all text above must be included in any redistribution + ****************************************************/ + +#include "Arduino_LCD.h" +//#include +#include +//#include "pins_arduino.h" +#include "wiring_private.h" +#include + + +// Constructor when using software SPI. All output pins are configurable. +Arduino_LCD::Arduino_LCD(uint8_t cs, uint8_t rs, uint8_t sid, uint8_t sclk, + uint8_t rst) : Adafruit_GFX(ILI9163C_TFTWIDTH, ILI9163C_TFTHEIGHT) +{ + _cs = cs; + _rs = rs; + _sid = sid; + _sclk = sclk; + _rst = rst; + hwSPI = false; +} + + +// Constructor when using hardware SPI. Faster, but must use SPI pins +// specific to each board type (e.g. 11,13 for Uno, 51,52 for Mega, etc.) +Arduino_LCD::Arduino_LCD(uint8_t cs, uint8_t rs, uint8_t rst) : + Adafruit_GFX(ILI9163C_TFTWIDTH, ILI9163C_TFTHEIGHT) { + _cs = cs; + _rs = rs; + _rst = rst; + hwSPI = true; + _sid = _sclk = 0; +} + + +inline void Arduino_LCD::spiwrite(uint8_t c) { + + //Serial.println(c, HEX); + +/* if (hwSPI) { + SPDR = c; + while(!(SPSR & _BV(SPIF))); + } else { + // Fast SPI bitbang swiped from LPD8806 library + for(uint8_t bit = 0x80; bit; bit >>= 1) { + if(c & bit) *dataport |= datapinmask; + else *dataport &= ~datapinmask; + *clkport |= clkpinmask; + *clkport &= ~clkpinmask; + } + } +*/ +SPI.transfer(c); +} + + +void Arduino_LCD::writecommand(uint8_t c) { +// *rsport &= ~rspinmask; +// *csport &= ~cspinmask; +digitalWrite(_rs, LOW); +digitalWrite(_cs, LOW); + + //Serial.print("C "); + spiwrite(c); +//SPI.transfer(c); +// *csport |= cspinmask; +digitalWrite(_cs, HIGH); +} + + +void Arduino_LCD::writedata(uint8_t c) { +// *rsport &= ~rspinmask; +// *csport &= ~cspinmask; +digitalWrite(_rs, HIGH); +digitalWrite(_cs, LOW); + + //Serial.print("D "); + spiwrite(c); +//SPI.transfer(c); +// *csport |= cspinmask; +digitalWrite(_cs, HIGH); +} + + +// Rather than a bazillion writecommand() and writedata() calls, screen +// initialization commands and arguments are organized in these tables +// stored in PROGMEM. The table may look bulky, but that's mostly the +// formatting -- storage-wise this is hundreds of bytes more compact +// than the equivalent code. Companion function follows. +#define DELAY 0x80 +//PROGMEM static prog_uchar +/*uint8_t + Bcmd[] = { // Initialization commands for 7735B screens + 18, // 18 commands in list: + ILI9163C_SWRESET, DELAY, // 1: Software reset, no args, w/delay + 50, // 50 ms delay + ILI9163C_SLPOUT , DELAY, // 2: Out of sleep mode, no args, w/delay + 255, // 255 = 500 ms delay + ILI9163C_COLMOD , 1+DELAY, // 3: Set color mode, 1 arg + delay: // I THINK THERE WAS SOMETHING HERE BECAUSE THE COMMAND IS CALLED 3A on Adafruits + 0x05, // 16-bit color + 10, // 10 ms delay + ILI9163C_FRMCTR1, 3+DELAY, // 4: Frame rate control, 3 args + delay: + 0x00, // fastest refresh + 0x06, // 6 lines front porch + 0x03, // 3 lines back porch + 10, // 10 ms delay + ILI9163C_MADCTL , 1 , // 5: Memory access ctrl (directions), 1 arg: + 0x08, // Row addr/col addr, bottom to top refresh + ILI9163C_DISSET5, 2 , // 6: Display settings #5, 2 args, no delay: + 0x15, // 1 clk cycle nonoverlap, 2 cycle gate + // rise, 3 cycle osc equalize + 0x02, // Fix on VTL + ILI9163C_INVCTR , 1 , // 7: Display inversion control, 1 arg: + 0x0, // Line inversion + ILI9163C_PWCTR1 , 2+DELAY, // 8: Power control, 2 args + delay: + 0x02, // GVDD = 4.7V + 0x70, // 1.0uA + 10, // 10 ms delay + ILI9163C_PWCTR2 , 1 , // 9: Power control, 1 arg, no delay: + 0x05, // VGH = 14.7V, VGL = -7.35V + ILI9163C_PWCTR3 , 2 , // 10: Power control, 2 args, no delay: + 0x01, // Opamp current small + 0x02, // Boost frequency + ILI9163C_VMCTR1 , 2+DELAY, // 11: Power control, 2 args + delay: + 0x3C, // VCOMH = 4V + 0x38, // VCOML = -1.1V + 10, // 10 ms delay + ILI9163C_PWCTR6 , 2 , // 12: Power control, 2 args, no delay: + 0x11, 0x15, + ILI9163C_GMCTRP1,16 , // 13: Magical unicorn dust, 16 args, no delay: + 0x09, 0x16, 0x09, 0x20, // (seriously though, not sure what + 0x21, 0x1B, 0x13, 0x19, // these config values represent) + 0x17, 0x15, 0x1E, 0x2B, + 0x04, 0x05, 0x02, 0x0E, + ILI9163C_GMCTRN1,16+DELAY, // 14: Sparkles and rainbows, 16 args + delay: + 0x0B, 0x14, 0x08, 0x1E, // (ditto) + 0x22, 0x1D, 0x18, 0x1E, + 0x1B, 0x1A, 0x24, 0x2B, + 0x06, 0x06, 0x02, 0x0F, + 10, // 10 ms delay + ILI9163C_CASET , 4 , // 15: Column addr set, 4 args, no delay: + 0x00, 0x02, // XSTART = 2 + 0x00, 0x81, // XEND = 129 + ILI9163C_RASET , 4 , // 16: Row addr set, 4 args, no delay: + 0x00, 0x02, // XSTART = 1 + 0x00, 0x81, // XEND = 160 + ILI9163C_NORON , DELAY, // 17: Normal display on, no args, w/delay + 10, // 10 ms delay + ILI9163C_DISPON , DELAY, // 18: Main screen turn on, no args, w/delay + 255 }, // 255 = 500 ms delay +*/ +uint8_t + Bcmd[] = { // Initialization commands for 7735B screens + 19, // 19 commands in list: + ILI9163C_SWRESET, DELAY, // 1: Software reset, no args, w/delay + 50, // 50 ms delay + 0x11 , DELAY, // 2: Out of sleep mode, no args, w/delay + 100, // 255 = 500 ms delay + 0x26 , 1, // 3: Set default gamma + 0x04, // 16-bit color + 0xb1, 2, // 4: Frame Rate + 0x0b, + 0x14, + 0xc0, 2, // 5: VRH1[4:0] & VC[2:0] + 0x08, + 0x00, + 0xc1, 1, // 6: BT[2:0] + 0x05, + 0xc5, 2, // 7: VMH[6:0] & VML[6:0] + 0x41, + 0x30, + 0xc7, 1, // 8: LCD Driving control + 0xc1, + 0xEC, 1, // 9: Set pumping color freq + 0x1b, + 0x3a , 1 + DELAY, // 10: Set color format + 0x55, // 16-bit color + 100, + 0x2a, 4, // 11: Set Column Address + 0x00, + 0x00, + 0x00, + 0x7f, + 0x2b, 4, // 12: Set Page Address + 0x00, + 0x00, + 0x00, + 0x9f, + 0x36, 1, // 12+1: Set Scanning Direction + 0xc8, + 0xb7, 1, // 14: Set Source Output Direciton + 0x00, + 0xf2, 1, // 15: Enable Gamma bit + 0x01, + 0xe0, 15 + DELAY, // 16: magic + 0x28, 0x24, 0x22, 0x31, + 0x2b, 0x0e, 0x53, 0xa5, + 0x42, 0x16, 0x18, 0x12, + 0x1a, 0x14, 0x03, + 50, + 0xe1, 15 + DELAY, // 17: more magic + 0x17, 0x1b, 0x1d, 0x0e, + 0x14, 0x11, 0x2c, 0xa5, + 0x3d, 0x09, 0x27, 0x2d, + 0x25, 0x2b, 0x3c, + 50, + ILI9163C_NORON , DELAY, // 18: Normal display on, no args, w/delay + 10, // 10 ms delay + ILI9163C_DISPON , DELAY, // 19: Main screen turn on, no args w/delay + 100 }, // 100 ms delay +Rcmd1[] = { // Init for 7735R, part 1 (red or green tab) + 15, // 15 commands in list: + ILI9163C_SWRESET, DELAY, // 1: Software reset, 0 args, w/delay + 150, // 150 ms delay + ILI9163C_SLPOUT , DELAY, // 2: Out of sleep mode, 0 args, w/delay + 255, // 500 ms delay + ILI9163C_FRMCTR1, 3 , // 3: Frame rate ctrl - normal mode, 3 args: + 0x01, 0x2C, 0x2D, // Rate = fosc/(1x2+40) * (LINE+2C+2D) + ILI9163C_FRMCTR2, 3 , // 4: Frame rate control - idle mode, 3 args: + 0x01, 0x2C, 0x2D, // Rate = fosc/(1x2+40) * (LINE+2C+2D) + ILI9163C_FRMCTR3, 6 , // 5: Frame rate ctrl - partial mode, 6 args: + 0x01, 0x2C, 0x2D, // Dot inversion mode + 0x01, 0x2C, 0x2D, // Line inversion mode + ILI9163C_INVCTR , 1 , // 6: Display inversion ctrl, 1 arg, no delay: + 0x07, // No inversion + ILI9163C_PWCTR1 , 3 , // 7: Power control, 3 args, no delay: + 0xA2, + 0x02, // -4.6V + 0x84, // AUTO mode + ILI9163C_PWCTR2 , 1 , // 8: Power control, 1 arg, no delay: + 0xC5, // VGH25 = 2.4C VGSEL = -10 VGH = 3 * AVDD + ILI9163C_PWCTR3 , 2 , // 9: Power control, 2 args, no delay: + 0x0A, // Opamp current small + 0x00, // Boost frequency + ILI9163C_PWCTR4 , 2 , // 10: Power control, 2 args, no delay: + 0x8A, // BCLK/2, Opamp current small & Medium low + 0x2A, + ILI9163C_PWCTR5 , 2 , // 11: Power control, 2 args, no delay: + 0x8A, 0xEE, + ILI9163C_VMCTR1 , 1 , // 12: Power control, 1 arg, no delay: + 0x0E, + ILI9163C_INVOFF , 0 , // 13: Don't invert display, no args, no delay + ILI9163C_MADCTL , 1 , // 14: Memory access control (directions), 1 arg: + 0xC8, // row addr/col addr, bottom to top refresh + ILI9163C_COLMOD , 1 , // 15: set color mode, 1 arg, no delay: + 0x05 }, // 16-bit color + + Rcmd2green[] = { // Init for 7735R, part 2 (green tab only) + 2, // 2 commands in list: + ILI9163C_CASET , 4 , // 1: Column addr set, 4 args, no delay: + 0x00, 0x02, // XSTART = 0 + 0x00, 0x7F+0x02, // XEND = 127 + ILI9163C_RASET , 4 , // 2: Row addr set, 4 args, no delay: + 0x00, 0x01, // XSTART = 0 + 0x00, 0x9F+0x01 }, // XEND = 159 + Rcmd2red[] = { // Init for 7735R, part 2 (red tab only) + 2, // 2 commands in list: + ILI9163C_CASET , 4 , // 1: Column addr set, 4 args, no delay: + 0x00, 0x00, // XSTART = 0 + 0x00, 0x7F, // XEND = 127 + ILI9163C_RASET , 4 , // 2: Row addr set, 4 args, no delay: + 0x00, 0x00, // XSTART = 0 + 0x00, 0x9F }, // XEND = 159 + + Rcmd3[] = { // Init for 7735R, part 3 (red or green tab) + 4, // 4 commands in list: + ILI9163C_GMCTRP1, 16 , // 1: Magical unicorn dust, 16 args, no delay: + 0x02, 0x1c, 0x07, 0x12, + 0x37, 0x32, 0x29, 0x2d, + 0x29, 0x25, 0x2B, 0x39, + 0x00, 0x01, 0x03, 0x10, + ILI9163C_GMCTRN1, 16 , // 2: Sparkles and rainbows, 16 args, no delay: + 0x03, 0x1d, 0x07, 0x06, + 0x2E, 0x2C, 0x29, 0x2D, + 0x2E, 0x2E, 0x37, 0x3F, + 0x00, 0x00, 0x02, 0x10, + ILI9163C_NORON , DELAY, // 3: Normal display on, no args, w/delay + 10, // 10 ms delay + ILI9163C_DISPON , DELAY, // 4: Main screen turn on, no args w/delay + 100 }; // 100 ms delay + + +// Companion code to the above tables. Reads and issues +// a series of LCD commands stored in PROGMEM byte array. +//void Arduino_LCD::commandList(prog_uchar *addr) { +void Arduino_LCD::commandList(uint8_t *addr) { + + uint8_t numCommands, numArgs; + uint16_t ms; + + numCommands = *addr++; // Number of commands to follow + while(numCommands--) { // For each command... + writecommand(*addr++); // Read, issue command + numArgs = *addr++; // Number of args to follow + ms = numArgs & DELAY; // If hibit set, delay follows args + numArgs &= ~DELAY; // Mask out delay bit + while(numArgs--) { // For each argument... + writedata(*addr++); // Read, issue argument + } + + if(ms) { + ms = *addr++; // Read post-command delay time (ms) + if(ms == 255) ms = 500; // If 255, delay for 500 ms + delay(ms); + } + } +} + + +// Initialization code common to both 'B' and 'R' type displays +//void Arduino_LCD::commonInit(prog_uchar *cmdList) { +void Arduino_LCD::commonInit(uint8_t *cmdList) { + + colstart = rowstart = 0; // May be overridden in init func + + pinMode(_rs, OUTPUT); + pinMode(_cs, OUTPUT); +/* + csport = portOutputRegister(digitalPinToPort(_cs)); + cspinmask = digitalPinToBitMask(_cs); + rsport = portOutputRegister(digitalPinToPort(_rs)); + rspinmask = digitalPinToBitMask(_rs); +*/ + +// if(hwSPI) { // Using hardware SPI + SPI.begin(); + SPI.setClockDivider(21); // 4 MHz (half speed) +// SPI.setClockDivider(SPI_CLOCK_DIV4); // 4 MHz (half speed) +// SPI.setBitOrder(MSBFIRST); +// there is no setBitOrder on the SPI library for the Due + SPI.setDataMode(SPI_MODE0); +/* + } else { + pinMode(_sclk, OUTPUT); + pinMode(_sid , OUTPUT); + clkport = portOutputRegister(digitalPinToPort(_sclk)); + clkpinmask = digitalPinToBitMask(_sclk); + dataport = portOutputRegister(digitalPinToPort(_sid)); + datapinmask = digitalPinToBitMask(_sid); + *clkport &= ~clkpinmask; + *dataport &= ~datapinmask; + } +*/ + + // toggle RST low to reset; CS low so it'll listen to us +// *csport &= ~cspinmask; + digitalWrite(_cs, LOW); + if (_rst) { + pinMode(_rst, OUTPUT); + digitalWrite(_rst, HIGH); + delay(500); + digitalWrite(_rst, LOW); + delay(500); + digitalWrite(_rst, HIGH); + delay(500); + } + + if(cmdList) commandList(cmdList); +} + + +// Initialization for ST7735B screens +void Arduino_LCD::initB(void) { + commonInit(Bcmd); + commandList(Rcmd3); +} + + +// Initialization for ST7735R screens (green or red tabs) +void Arduino_LCD::initR(uint8_t options) { + commonInit(Rcmd1); + if(options == INITR_GREENTAB) { + commandList(Rcmd2green); + colstart = 2; + rowstart = 1; + } else { + // colstart, rowstart left at default '0' values + commandList(Rcmd2red); + } + commandList(Rcmd3); +} + + +void Arduino_LCD::setAddrWindow(uint8_t x0, uint8_t y0, uint8_t x1, + uint8_t y1) { + + writecommand(ILI9163C_CASET); // Column addr set + writedata(0x00); + writedata(x0+colstart); // XSTART + writedata(0x00); + writedata(x1+colstart); // XEND + + writecommand(ILI9163C_RASET); // Row addr set + writedata(0x00); + writedata(y0+rowstart); // YSTART + writedata(0x00); + writedata(y1+rowstart); // YEND + + writecommand(ILI9163C_RAMWR); // write to RAM +} + + +void Arduino_LCD::fillScreen(uint16_t color) { + + uint8_t x, y, hi = color >> 8, lo = color; + + setAddrWindow(0, 0, _width-1, _height-1); + +// *rsport |= rspinmask; +// *csport &= ~cspinmask; +digitalWrite(_rs, HIGH); + digitalWrite(_cs, LOW); + + for(y=_height; y>0; y--) { + for(x=_width; x>0; x--) { +//SPI.transfer(hi); +//SPI.transfer(lo); + spiwrite(hi); + spiwrite(lo); + } + } + +// *csport |= cspinmask; + digitalWrite(_cs, HIGH); +} + + +void Arduino_LCD::pushColor(uint16_t color) { +// *rsport |= rspinmask; +// *csport &= ~cspinmask; +digitalWrite(_rs, HIGH); + digitalWrite(_cs, LOW); + + spiwrite(color >> 8); + spiwrite(color); +//SPI.transfer(color>>8); +//SPI.transfer(color); + +// *csport |= cspinmask; + digitalWrite(_cs, HIGH); +} + + +void Arduino_LCD::drawPixel(int16_t x, int16_t y, uint16_t color) { + + if((x < 0) ||(x >= _width) || (y < 0) || (y >= _height)) return; + + setAddrWindow(x,y,x+1,y+1); + +// *rsport |= rspinmask; +// *csport &= ~cspinmask; +digitalWrite(_rs, HIGH); + digitalWrite(_cs, LOW); + + spiwrite(color >> 8); + spiwrite(color); +//SPI.transfer(color>>8); +//SPI.transfer(color); + +// *csport |= cspinmask; + digitalWrite(_cs, HIGH); +} + + +void Arduino_LCD::drawFastVLine(int16_t x, int16_t y, int16_t h, + uint16_t color) { + + // Rudimentary clipping + if((x >= _width) || (y >= _height)) return; + if((y+h-1) >= _height) h = _height-y; + setAddrWindow(x, y, x, y+h-1); + + uint8_t hi = color >> 8, lo = color; +// *rsport |= rspinmask; +// *csport &= ~cspinmask; +digitalWrite(_rs, HIGH); + digitalWrite(_cs, LOW); + while (h--) { + spiwrite(hi); + spiwrite(lo); +//SPI.transfer(hi); +//SPI.transfer(lo); + } +// *csport |= cspinmask; + digitalWrite(_cs, HIGH); +} + + +void Arduino_LCD::drawFastHLine(int16_t x, int16_t y, int16_t w, + uint16_t color) { + + // Rudimentary clipping + if((x >= _width) || (y >= _height)) return; + if((x+w-1) >= _width) w = _width-x; + setAddrWindow(x, y, x+w-1, y); + + uint8_t hi = color >> 8, lo = color; +// *rsport |= rspinmask; +// *csport &= ~cspinmask; +digitalWrite(_rs, HIGH); + digitalWrite(_cs, LOW); + while (w--) { + spiwrite(hi); + spiwrite(lo); +//SPI.transfer(hi); +//SPI.transfer(lo); + } +// *csport |= cspinmask; + digitalWrite(_cs, HIGH); +} + + +// fill a rectangle +void Arduino_LCD::fillRect(int16_t x, int16_t y, int16_t w, int16_t h, + uint16_t color) { + + // rudimentary clipping (drawChar w/big text requires this) + if((x >= _width) || (y >= _height)) return; + if((x + w - 1) >= _width) w = _width - x; + if((y + h - 1) >= _height) h = _height - y; + + setAddrWindow(x, y, x+w-1, y+h-1); + + uint8_t hi = color >> 8, lo = color; +// *rsport |= rspinmask; +// *csport &= ~cspinmask; +digitalWrite(_rs, HIGH); +digitalWrite(_cs, LOW); + for(y=h; y>0; y--) { + for(x=w; x>0; x--) { + spiwrite(hi); + spiwrite(lo); +//SPI.transfer(hi); +//SPI.transfer(lo); + } + } + +// *csport |= cspinmask; +digitalWrite(_cs, HIGH); +} + + +// Pass 8-bit (each) R,G,B, get back 16-bit packed color +uint16_t Arduino_LCD::Color565(uint8_t r, uint8_t g, uint8_t b) { + return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3); +} + + +#define MADCTL_MY 0x80 +#define MADCTL_MX 0x40 +#define MADCTL_MV 0x20 +#define MADCTL_ML 0x10 +#define MADCTL_RGB 0x08 +#define MADCTL_MH 0x04 + +void Arduino_LCD::setRotation(uint8_t m) { + + writecommand(ILI9163C_MADCTL); + rotation = m % 4; // can't be higher than 3 + switch (rotation) { + case 0: + writedata(MADCTL_MX | MADCTL_MY | MADCTL_RGB); + _width = ILI9163C_TFTWIDTH; + _height = ILI9163C_TFTHEIGHT; + break; + case 1: + writedata(MADCTL_MY | MADCTL_MV | MADCTL_RGB); + _width = ILI9163C_TFTHEIGHT; + _height = ILI9163C_TFTWIDTH; + break; + case 2: + writedata(MADCTL_RGB); + _width = ILI9163C_TFTWIDTH; + _height = ILI9163C_TFTHEIGHT; + break; + case 3: + writedata(MADCTL_MX | MADCTL_MV | MADCTL_RGB); + _width = ILI9163C_TFTHEIGHT; + _height = ILI9163C_TFTWIDTH; + break; + } +} + + +void Arduino_LCD::invertDisplay(boolean i) { + writecommand(i ? ILI9163C_INVON : ILI9163C_INVOFF); +} + +/* + 18, // there are 17 commands + ILI9163C_SWRESET, DELAY, // 1: Software reset, no args, w/delay + 50, // 50 ms delay + + 0x11, //Exit Sleep + DELAY,50, + + 0x26, //Set Default Gamma + 0x104, + + //0xF2, //E0h & E1h Enable/Disable + //0x100, + + 0xB1, + 0x10C, + 0x114, + + 0xC0, //Set VRH1[4:0] & VC[2:0] for VCI1 & GVDD + 0x10C, + 0x105, + + 0xC1, //Set BT[2:0] for AVDD & VCL & VGH & VGL + 0x102, + + 0xC5, //Set VMH[6:0] & VML[6:0] for VOMH & VCOML + 0x129, + 0x143, + + 0xC7, + 0x140, + + 0x3a, //Set Color Format + 0x105, + + 0x2A, //Set Column Address + 0x100, + 0x100, + 0x100, + 0x17F, + + 0x2B, //Set Page Address + 0x100, + 0x100, + 0x100, + 0x19F, + + 0x36, //Set Scanning Direction, RGB + 0x1C0, + + 0xB7, //Set Source Output Direction + 0x100, + + 0xf2, //Enable Gamma bit + 0x101, + + 0xE0, + 0x136,//p1 + 0x129,//p2 + 0x112,//p3 + 0x122,//p4 + 0x11C,//p5 + 0x115,//p6 + 0x142,//p7 + 0x1B7,//p8 + 0x12F,//p9 + 0x113,//p10 + 0x112,//p11 + 0x10A,//p12 + 0x111,//p13 + 0x10B,//p14 + 0x106,//p15 + + 0xE1, + 0x109,//p1 + 0x116,//p2 + 0x12D,//p3 + 0x10D,//p4 + 0x113,//p5 + 0x115,//p6 + 0x140,//p7 + 0x148,//p8 + 0x153,//p9 + 0x10C,//p10 + 0x11D,//p11 + 0x125,//p12 + 0x12E,//p13 + 0x134,//p14 + 0x139,//p15 + + 0x33, // scroll setup + 0x100, + 0x100, + 0x100, + 0x1C1, + 0x100, + 0x100, + + 0x29, // Display On + 0x2C}, // write gram + +*/ + diff --git a/libraries/Robot_Control/Arduino_LCD.h b/libraries/Robot_Control/Arduino_LCD.h new file mode 100644 index 00000000000..954251e30d6 --- /dev/null +++ b/libraries/Robot_Control/Arduino_LCD.h @@ -0,0 +1,141 @@ +/*************************************************** + This is a library for the Adafruit 1.8" SPI display. + This library works with the Adafruit 1.8" TFT Breakout w/SD card + ----> http://www.adafruit.com/products/358 + as well as Adafruit raw 1.8" TFT display + ----> http://www.adafruit.com/products/618 + + Check out the links above for our tutorials and wiring diagrams + These displays use SPI to communicate, 4 or 5 pins are required to + interface (RST is optional) + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing + products from Adafruit! + + Written by Limor Fried/Ladyada for Adafruit Industries. + MIT license, all text above must be included in any redistribution + ****************************************************/ + +#ifndef _ARDUINO_LCDH_ +#define _ARDUINO_LCDH_ + +#if ARDUINO >= 100 + #include "Arduino.h" + #include "Print.h" +#else + #include "WProgram.h" +#endif +#include "utility/Adafruit_GFX.h" +//#include + +// some flags for initR() :( +#define INITR_GREENTAB 0x0 +#define INITR_REDTAB 0x1 + +#define ILI9163C_TFTWIDTH 128 +#define ILI9163C_TFTHEIGHT 160 + +#define ILI9163C_NOP 0x00 +#define ILI9163C_SWRESET 0x01 +#define ILI9163C_RDDID 0x04 +#define ILI9163C_RDDST 0x09 + +#define ILI9163C_SLPIN 0x10 +#define ILI9163C_SLPOUT 0x11 +#define ILI9163C_PTLON 0x12 +#define ILI9163C_NORON 0x13 + +#define ILI9163C_INVOFF 0x20 +#define ILI9163C_INVON 0x21 +#define ILI9163C_DISPOFF 0x28 +#define ILI9163C_DISPON 0x29 +#define ILI9163C_CASET 0x2A +#define ILI9163C_RASET 0x2B +#define ILI9163C_RAMWR 0x2C +#define ILI9163C_RAMRD 0x2E + +#define ILI9163C_PTLAR 0x30 +#define ILI9163C_COLMOD 0x3A // this is interface pixel format, this might be the issue +#define ILI9163C_MADCTL 0x36 + +#define ILI9163C_FRMCTR1 0xB1 +#define ILI9163C_FRMCTR2 0xB2 +#define ILI9163C_FRMCTR3 0xB3 +#define ILI9163C_INVCTR 0xB4 +#define ILI9163C_DISSET5 0xB6 + +#define ILI9163C_PWCTR1 0xC0 +#define ILI9163C_PWCTR2 0xC1 +#define ILI9163C_PWCTR3 0xC2 +#define ILI9163C_PWCTR4 0xC3 +#define ILI9163C_PWCTR5 0xC4 +#define ILI9163C_VMCTR1 0xC5 + +#define ILI9163C_RDID1 0xDA +#define ILI9163C_RDID2 0xDB +#define ILI9163C_RDID3 0xDC +#define ILI9163C_RDID4 0xDD + +#define ILI9163C_PWCTR6 0xFC + +#define ILI9163C_GMCTRP1 0xE0 +#define ILI9163C_GMCTRN1 0xE1 + +// Color definitions +#define ILI9163C_BLACK 0x0000 +#define ILI9163C_BLUE 0x001F +#define ILI9163C_RED 0xF800 +#define ILI9163C_GREEN 0x07E0 +#define ILI9163C_CYAN 0x07FF +#define ILI9163C_MAGENTA 0xF81F +#define ILI9163C_YELLOW 0xFFE0 +#define ILI9163C_WHITE 0xFFFF + + +class Arduino_LCD : public Adafruit_GFX { + + public: + + Arduino_LCD(uint8_t CS, uint8_t RS, uint8_t SID, uint8_t SCLK, uint8_t RST); + Arduino_LCD(uint8_t CS, uint8_t RS, uint8_t RST); + + void initB(void), // for ST7735B displays + initR(uint8_t options = INITR_GREENTAB), // for ST7735R + setAddrWindow(uint8_t x0, uint8_t y0, uint8_t x1, uint8_t y1), + pushColor(uint16_t color), + fillScreen(uint16_t color), + drawPixel(int16_t x, int16_t y, uint16_t color), + drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color), + drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color), + fillRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color), + setRotation(uint8_t r), + invertDisplay(boolean i); + uint16_t Color565(uint8_t r, uint8_t g, uint8_t b); + + /* These are not for current use, 8-bit protocol only! + uint8_t readdata(void), + readcommand8(uint8_t); + uint16_t readcommand16(uint8_t); + uint32_t readcommand32(uint8_t); + void dummyclock(void); + */ + + private: + + void spiwrite(uint8_t), + writecommand(uint8_t c), + writedata(uint8_t d), +// commandList(prog_uchar *addr), +// commonInit(prog_uchar *cmdList); + commandList(uint8_t *addr), + commonInit(uint8_t *cmdList); +//uint8_t spiread(void); + + boolean hwSPI; + volatile uint8_t *dataport, *clkport, *csport, *rsport; + uint8_t _cs, _rs, _rst, _sid, _sclk, + datapinmask, clkpinmask, cspinmask, rspinmask, + colstart, rowstart; // some displays need this changed +}; + +#endif diff --git a/libraries/Robot_Control/Compass.cpp b/libraries/Robot_Control/Compass.cpp new file mode 100644 index 00000000000..1b1ef3149ab --- /dev/null +++ b/libraries/Robot_Control/Compass.cpp @@ -0,0 +1,34 @@ +#include "Compass.h" +#include + +void Compass::begin(){ + Wire.begin(); +} +float Compass::getReading(){ + _beginTransmission(); + _endTransmission(); + + //time delays required by HMC6352 upon receipt of the command + //Get Data. Compensate and Calculate New Heading : 6ms + delay(6); + + Wire.requestFrom(HMC6352SlaveAddress, 2); //get the two data bytes, MSB and LSB + + //"The heading output data will be the value in tenths of degrees + //from zero to 3599 and provided in binary format over the two bytes." + byte MSB = Wire.read(); + byte LSB = Wire.read(); + + float headingSum = (MSB << 8) + LSB; //(MSB / LSB sum) + float headingInt = headingSum / 10; + + return headingInt; +} + +void Compass::_beginTransmission(){ + Wire.beginTransmission(HMC6352SlaveAddress); + Wire.write(HMC6352ReadAddress); +} +void Compass::_endTransmission(){ + Wire.endTransmission(); +} \ No newline at end of file diff --git a/libraries/Robot_Control/Compass.h b/libraries/Robot_Control/Compass.h new file mode 100644 index 00000000000..aa085a98a80 --- /dev/null +++ b/libraries/Robot_Control/Compass.h @@ -0,0 +1,24 @@ +#ifndef Compass_h +#define Compass_h + +#if ARDUINO >= 100 +#include "Arduino.h" +#else +#include "WProgram.h" +#endif + +//0x21==0x42>>1, from bildr's code +#define HMC6352SlaveAddress 0x21 +#define HMC6352ReadAddress 0x41 + +class Compass{ + public: + void begin(); + float getReading(); + private: + void _beginTransmission(); + void _endTransmission(); + +}; + +#endif \ No newline at end of file diff --git a/libraries/Robot_Control/EEPROM_I2C.cpp b/libraries/Robot_Control/EEPROM_I2C.cpp new file mode 100644 index 00000000000..dd12695f14b --- /dev/null +++ b/libraries/Robot_Control/EEPROM_I2C.cpp @@ -0,0 +1,62 @@ +#include "EEPROM_I2C.h" +#include + +#if ARDUINO >= 100 +#include "Arduino.h" +#else +#include "WProgram.h" +#endif + +void EEPROM_I2C::begin(){ + Wire.begin(); +} + +void EEPROM_I2C::writeByte(unsigned int eeaddress, byte data){ + int rdata = data; + this->_beginTransmission(eeaddress); + Wire.write(rdata); + this->_endTransmission(); +} + +byte EEPROM_I2C::readByte(unsigned int eeaddress){ + int rdata; + this->_beginTransmission(eeaddress); + this->_endTransmission(); + + Wire.requestFrom(DEVICEADDRESS,1); + if (Wire.available()) rdata = Wire.read(); + return rdata; +} + +void EEPROM_I2C::writePage(unsigned int eeaddress, byte* data, byte length ){ + this->_beginTransmission(eeaddress); + + byte c; + + for ( c = 0; c < length; c++) + Wire.write(data[c]); + + this->_endTransmission(); + + delay(10); // need some delay +} + +void EEPROM_I2C::readBuffer(unsigned int eeaddress, byte *buffer, int length ){ + this->_beginTransmission(eeaddress); + this->_endTransmission(); + Wire.requestFrom(DEVICEADDRESS,length); + + for ( int c = 0; c < length; c++ ) + if (Wire.available()) buffer[c] = Wire.read(); +} + + + +void EEPROM_I2C::_beginTransmission(unsigned int eeaddress){ + Wire.beginTransmission(DEVICEADDRESS); + Wire.write((eeaddress >> 8)); // Address High Byte + Wire.write((eeaddress & 0xFF)); // Address Low Byte +} +void EEPROM_I2C::_endTransmission(){ + Wire.endTransmission(); +} \ No newline at end of file diff --git a/libraries/Robot_Control/EEPROM_I2C.h b/libraries/Robot_Control/EEPROM_I2C.h new file mode 100644 index 00000000000..9bd0f6af63b --- /dev/null +++ b/libraries/Robot_Control/EEPROM_I2C.h @@ -0,0 +1,31 @@ +#ifndef EEPROM_I2C_h +#define EEPROM_I2C_h + +#if ARDUINO >= 100 +#include "Arduino.h" +#else +#include "WProgram.h" +#endif + +#define EE24LC512MAXBYTES 64000 +#define DEVICEADDRESS 0x50 + +class EEPROM_I2C{ + public: + void begin(); + + void writeByte(unsigned int eeaddresspage, byte data); + byte readByte(unsigned int eeaddresspage); + + void writePage(unsigned int eeaddresspage, byte* data, byte length ); + void readBuffer(unsigned int eeaddress, byte *buffer, int length ); + + //uint16_t readPixel(uint16_t theMemoryAddress); + //void readImage(uint16_t theMemoryAddress, int width, int height); + + protected: + void _beginTransmission(unsigned int eeaddress); + void _endTransmission(); +}; + +#endif \ No newline at end of file diff --git a/libraries/Robot_Control/EasyTransfer2.cpp b/libraries/Robot_Control/EasyTransfer2.cpp new file mode 100644 index 00000000000..24427cc6e71 --- /dev/null +++ b/libraries/Robot_Control/EasyTransfer2.cpp @@ -0,0 +1,152 @@ +#include "EasyTransfer2.h" + + + + +//Captures address and size of struct +void EasyTransfer2::begin(HardwareSerial *theSerial){ + _serial = theSerial; + + //dynamic creation of rx parsing buffer in RAM + //rx_buffer = (uint8_t*) malloc(size); + + resetData(); +} + +void EasyTransfer2::writeByte(uint8_t dat){ + if(position<20) + data[position++]=dat; + size++; +} +void EasyTransfer2::writeInt(int dat){ + if(position<19){ + data[position++]=dat>>8; + data[position++]=dat; + size+=2; + } +} +uint8_t EasyTransfer2::readByte(){ + if(position>=size)return 0; + return data[position++]; +} +int EasyTransfer2::readInt(){ + if(position+1>=size)return 0; + int dat_1=data[position++]<<8; + int dat_2=data[position++]; + int dat= dat_1 | dat_2; + return dat; +} + +void EasyTransfer2::resetData(){ + for(int i=0;i<20;i++){ + data[i]=0; + } + size=0; + position=0; +} + +//Sends out struct in binary, with header, length info and checksum +void EasyTransfer2::sendData(){ + uint8_t CS = size; + _serial->write(0x06); + _serial->write(0x85); + _serial->write(size); + for(int i = 0; iwrite(*(data+i)); + //Serial.print(*(data+i)); + //Serial.print(","); + } + //Serial.println(""); + _serial->write(CS); + + resetData(); +} + +boolean EasyTransfer2::receiveData(){ + + //start off by looking for the header bytes. If they were already found in a previous call, skip it. + if(rx_len == 0){ + //this size check may be redundant due to the size check below, but for now I'll leave it the way it is. + if(_serial->available() >= 3){ + //this will block until a 0x06 is found or buffer size becomes less then 3. + while(_serial->read() != 0x06) { + //This will trash any preamble junk in the serial buffer + //but we need to make sure there is enough in the buffer to process while we trash the rest + //if the buffer becomes too empty, we will escape and try again on the next call + if(_serial->available() < 3) + return false; + } + //Serial.println("head"); + if (_serial->read() == 0x85){ + rx_len = _serial->read(); + //Serial.print("rx_len:"); + //Serial.println(rx_len); + resetData(); + + //make sure the binary structs on both Arduinos are the same size. + /*if(rx_len != size){ + rx_len = 0; + return false; + }*/ + } + } + //Serial.println("nothing"); + } + + //we get here if we already found the header bytes, the struct size matched what we know, and now we are byte aligned. + if(rx_len != 0){ + + while(_serial->available() && rx_array_inx <= rx_len){ + data[rx_array_inx++] = _serial->read(); + } + + if(rx_len == (rx_array_inx-1)){ + //seem to have got whole message + //last uint8_t is CS + calc_CS = rx_len; + //Serial.print("len:"); + //Serial.println(rx_len); + for (int i = 0; i +* +*This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License. +*To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/ or +*send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA. +******************************************************************/ +#ifndef EasyTransfer2_h +#define EasyTransfer2_h + + +//make it a little prettier on the front end. +#define details(name) (byte*)&name,sizeof(name) + +//Not neccessary, but just in case. +#if ARDUINO > 22 +#include "Arduino.h" +#else +#include "WProgram.h" +#endif +#include "HardwareSerial.h" +//#include +#include +#include +#include +#include + +class EasyTransfer2 { +public: +void begin(HardwareSerial *theSerial); +//void begin(uint8_t *, uint8_t, NewSoftSerial *theSerial); +void sendData(); +boolean receiveData(); + +void writeByte(uint8_t dat); +void writeInt(int dat); +uint8_t readByte(); +int readInt(); + + +private: +HardwareSerial *_serial; + +void resetData(); + +uint8_t data[20]; //data storage, for both read and send +uint8_t position; +uint8_t size; //size of data in bytes. Both for read and send +//uint8_t * address; //address of struct +//uint8_t size; //size of struct +//uint8_t * rx_buffer; //address for temporary storage and parsing buffer +//uint8_t rx_buffer[20]; +uint8_t rx_array_inx; //index for RX parsing buffer +uint8_t rx_len; //RX packet length according to the packet +uint8_t calc_CS; //calculated Chacksum +}; + + + +#endif \ No newline at end of file diff --git a/libraries/Robot_Control/Fat16.cpp b/libraries/Robot_Control/Fat16.cpp new file mode 100644 index 00000000000..aa8f585e95c --- /dev/null +++ b/libraries/Robot_Control/Fat16.cpp @@ -0,0 +1,990 @@ +/* Arduino FAT16 Library + * Copyright (C) 2008 by William Greiman + * + * This file is part of the Arduino FAT16 Library + * + * This Library is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This Library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with the Arduino Fat16 Library. If not, see + * . + */ +#include +#if ARDUINO < 100 +#include +#else // ARDUINO +#include +#endif // ARDUINO +#include +//----------------------------------------------------------------------------- +// volume info +uint8_t Fat16::volumeInitialized_ = 0; // true if FAT16 volume is valid +uint8_t Fat16::fatCount_; // number of file allocation tables +uint8_t Fat16::blocksPerCluster_; // must be power of 2 +uint16_t Fat16::rootDirEntryCount_; // should be 512 for FAT16 +fat_t Fat16::blocksPerFat_; // number of blocks in one FAT +fat_t Fat16::clusterCount_; // total clusters in volume +uint32_t Fat16::fatStartBlock_; // start of first FAT +uint32_t Fat16::rootDirStartBlock_; // start of root dir +uint32_t Fat16::dataStartBlock_; // start of data clusters +//------------------------------------------------------------------------------ +// raw block cache +SdCard *Fat16::rawDev_ = 0; // class for block read and write +uint32_t Fat16::cacheBlockNumber_ = 0XFFFFFFFF; // init to invalid block number +cache16_t Fat16::cacheBuffer_; // 512 byte cache for SdCard +uint8_t Fat16::cacheDirty_ = 0; // cacheFlush() will write block if true +uint32_t Fat16::cacheMirrorBlock_ = 0; // mirror block for second FAT +//------------------------------------------------------------------------------ +// callback function for date/time +void (*Fat16::dateTime_)(uint16_t* date, uint16_t* time) = NULL; + +#if ALLOW_DEPRECATED_FUNCTIONS +void (*Fat16::oldDateTime_)(uint16_t& date, uint16_t& time) = NULL; // NOLINT +#endif // ALLOW_DEPRECATED_FUNCTIONS +//------------------------------------------------------------------------------ +// format 8.3 name for directory entry +static uint8_t make83Name(const char* str, uint8_t* name) { + uint8_t c; + uint8_t n = 7; // max index for part before dot + uint8_t i = 0; + // blank fill name and extension + while (i < 11) name[i++] = ' '; + i = 0; + while ((c = *str++) != '\0') { + if (c == '.') { + if (n == 10) return false; // only one dot allowed + n = 10; // max index for full 8.3 name + i = 8; // place for extension + } else { + // illegal FAT characters + PGM_P p = PSTR("|<>^+=?/[];,*\"\\"); + uint8_t b; + while ((b = pgm_read_byte(p++))) if (b == c) return false; + // check length and only allow ASCII printable characters + if (i > n || c < 0X21 || c > 0X7E) return false; + // only upper case allowed in 8.3 names - convert lower to upper + name[i++] = c < 'a' || c > 'z' ? c : c + ('A' - 'a'); + } + } + // must have a file name, extension is optional + return name[0] != ' '; +} +//============================================================================== +// Fat16 member functions +//------------------------------------------------------------------------------ +uint8_t Fat16::addCluster(void) { + // start search after last cluster of file or at cluster two in FAT + fat_t freeCluster = curCluster_ ? curCluster_ : 1; + for (fat_t i = 0; ; i++) { + // return no free clusters + if (i >= clusterCount_) return false; + // Fat has clusterCount + 2 entries + if (freeCluster > clusterCount_) freeCluster = 1; + freeCluster++; + fat_t value; + if (!fatGet(freeCluster, &value)) return false; + if (value == 0) break; + } + // mark cluster allocated + if (!fatPut(freeCluster, FAT16EOC)) return false; + + if (curCluster_ != 0) { + // link cluster to chain + if (!fatPut(curCluster_, freeCluster)) return false; + } else { + // first cluster of file so update directory entry + flags_ |= F_FILE_DIR_DIRTY; + firstCluster_ = freeCluster; + } + curCluster_ = freeCluster; + return true; +} +//------------------------------------------------------------------------------ +// +dir_t* Fat16::cacheDirEntry(uint16_t index, uint8_t action) { + if (index >= rootDirEntryCount_) return NULL; + if (!cacheRawBlock(rootDirStartBlock_ + (index >> 4), action)) return NULL; + return &cacheBuffer_.dir[index & 0XF]; +} +//------------------------------------------------------------------------------ +// +uint8_t Fat16::cacheFlush(void) { + if (cacheDirty_) { + if (!rawDev_->writeBlock(cacheBlockNumber_, cacheBuffer_.data)) { + return false; + } + // mirror FAT tables + if (cacheMirrorBlock_) { + if (!rawDev_->writeBlock(cacheMirrorBlock_, cacheBuffer_.data)) { + return false; + } + cacheMirrorBlock_ = 0; + } + cacheDirty_ = 0; + } + return true; +} +//------------------------------------------------------------------------------ +// +uint8_t Fat16::cacheRawBlock(uint32_t blockNumber, uint8_t action) { + if (cacheBlockNumber_ != blockNumber) { + if (!cacheFlush()) return false; + if (!rawDev_->readBlock(blockNumber, cacheBuffer_.data)) return false; + cacheBlockNumber_ = blockNumber; + } + cacheDirty_ |= action; + return true; +} +//------------------------------------------------------------------------------ +/** + * Close a file and force cached data and directory information + * to be written to the storage device. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + * Reasons for failure include no file is open or an I/O error. + */ +uint8_t Fat16::close(void) { + if (!sync()) return false; + flags_ = 0; + return true; +} +//------------------------------------------------------------------------------ +/** + * Return a files directory entry + * + * \param[out] dir Location for return of the files directory entry. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +uint8_t Fat16::dirEntry(dir_t* dir) { + if (!sync()) return false; + dir_t* p = cacheDirEntry(dirEntryIndex_, CACHE_FOR_WRITE); + if (!p) return false; + memcpy(dir, p, sizeof(dir_t)); + return true; +} +//------------------------------------------------------------------------------ +uint8_t Fat16::fatGet(fat_t cluster, fat_t* value) { + if (cluster > (clusterCount_ + 1)) return false; + uint32_t lba = fatStartBlock_ + (cluster >> 8); + if (lba != cacheBlockNumber_) { + if (!cacheRawBlock(lba)) return false; + } + *value = cacheBuffer_.fat[cluster & 0XFF]; + return true; +} +//------------------------------------------------------------------------------ +uint8_t Fat16::fatPut(fat_t cluster, fat_t value) { + if (cluster < 2) return false; + if (cluster > (clusterCount_ + 1)) return false; + uint32_t lba = fatStartBlock_ + (cluster >> 8); + if (lba != cacheBlockNumber_) { + if (!cacheRawBlock(lba)) return false; + } + cacheBuffer_.fat[cluster & 0XFF] = value; + cacheSetDirty(); + // mirror second FAT + if (fatCount_ > 1) cacheMirrorBlock_ = lba + blocksPerFat_; + return true; +} +//------------------------------------------------------------------------------ +// free a cluster chain +uint8_t Fat16::freeChain(fat_t cluster) { + while (1) { + fat_t next; + if (!fatGet(cluster, &next)) return false; + if (!fatPut(cluster, 0)) return false; + if (isEOC(next)) return true; + cluster = next; + } +} +//------------------------------------------------------------------------------ +/** + * Initialize a FAT16 volume. + * + * \param[in] dev The SdCard where the volume is located. + * + * \param[in] part The partition to be used. Legal values for \a part are + * 1-4 to use the corresponding partition on a device formatted with + * a MBR, Master Boot Record, or zero if the device is formatted as + * a super floppy with the FAT boot sector in block zero. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. reasons for + * failure include not finding a valid FAT16 file system in the + * specified partition, a call to init() after a volume has + * been successful initialized or an I/O error. + * + */ +uint8_t Fat16::init(SdCard* dev, uint8_t part) { + // error if invalid partition + if (part > 4) return false; + rawDev_ = dev; + uint32_t volumeStartBlock = 0; + // if part == 0 assume super floppy with FAT16 boot sector in block zero + // if part > 0 assume mbr volume with partition table + if (part) { + if (!cacheRawBlock(volumeStartBlock)) return false; + volumeStartBlock = cacheBuffer_.mbr.part[part - 1].firstSector; + } + if (!cacheRawBlock(volumeStartBlock)) return false; + // check boot block signature + if (cacheBuffer_.data[510] != BOOTSIG0 || + cacheBuffer_.data[511] != BOOTSIG1) return false; + bpb_t* bpb = &cacheBuffer_.fbs.bpb; + fatCount_ = bpb->fatCount; + blocksPerCluster_ = bpb->sectorsPerCluster; + blocksPerFat_ = bpb->sectorsPerFat16; + rootDirEntryCount_ = bpb->rootDirEntryCount; + fatStartBlock_ = volumeStartBlock + bpb->reservedSectorCount; + rootDirStartBlock_ = fatStartBlock_ + bpb->fatCount*bpb->sectorsPerFat16; + dataStartBlock_ = rootDirStartBlock_ + + ((32*bpb->rootDirEntryCount + 511)/512); + uint32_t totalBlocks = bpb->totalSectors16 ? + bpb->totalSectors16 : bpb->totalSectors32; + clusterCount_ = (totalBlocks - (dataStartBlock_ - volumeStartBlock)) + /bpb->sectorsPerCluster; + // verify valid FAT16 volume + if (bpb->bytesPerSector != 512 // only allow 512 byte blocks + || bpb->sectorsPerFat16 == 0 // zero for FAT32 + || clusterCount_ < 4085 // FAT12 if true + || totalBlocks > 0X800000 // Max size for FAT16 volume + || bpb->reservedSectorCount == 0 // invalid volume + || bpb->fatCount == 0 // invalid volume + || bpb->sectorsPerFat16 < (clusterCount_ >> 8) // invalid volume + || bpb->sectorsPerCluster == 0 // invalid volume + // power of 2 test + || bpb->sectorsPerCluster & (bpb->sectorsPerCluster - 1)) { + // not a usable FAT16 bpb + return false; + } + volumeInitialized_ = 1; + return true; +} +//------------------------------------------------------------------------------ +/** List directory contents to Serial. + * + * \param[in] flags The inclusive OR of + * + * LS_DATE - %Print file modification date + * + * LS_SIZE - %Print file size. + */ +void Fat16::ls(uint8_t flags) { + dir_t d; + for (uint16_t index = 0; readDir(&d, &index, DIR_ATT_VOLUME_ID); index++) { + // print file name with possible blank fill + printDirName(d, flags & (LS_DATE | LS_SIZE) ? 14 : 0); + + // print modify date/time if requested + if (flags & LS_DATE) { + printFatDate(d.lastWriteDate); + Serial.write(' '); + printFatTime(d.lastWriteTime); + } + + // print size if requested + if (DIR_IS_FILE(&d) && (flags & LS_SIZE)) { + Serial.write(' '); + Serial.print(d.fileSize); + } + Serial.println(); + } +} +//------------------------------------------------------------------------------ +/** + * Open a file by file name. + * + * \note The file must be in the root directory and must have a DOS + * 8.3 name. + * + * \param[in] fileName A valid 8.3 DOS name for a file in the root directory. + * + * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive + * OR of flags from the following list + * + * O_READ - Open for reading. + * + * O_RDONLY - Same as O_READ. + * + * O_WRITE - Open for writing. + * + * O_WRONLY - Same as O_WRITE. + * + * O_RDWR - Open for reading and writing. + * + * O_APPEND - If set, the file offset shall be set to the end of the + * file prior to each write. + * + * O_CREAT - If the file exists, this flag has no effect except as noted + * under O_EXCL below. Otherwise, the file shall be created + * + * O_EXCL - If O_CREAT and O_EXCL are set, open() shall fail if the file exists. + * + * O_SYNC - Call sync() after each write. This flag should not be used with + * write(uint8_t), write_P(PGM_P), writeln_P(PGM_P), or the Arduino Print class. + * These functions do character a time writes so sync() will be called + * after each byte. + * + * O_TRUNC - If the file exists and is a regular file, and the file is + * successfully opened and is not read only, its length shall be truncated to 0. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + * Reasons for failure include the FAT volume has not been initialized, + * a file is already open, \a fileName is invalid, the file does not exist, + * is a directory, or can't be opened in the access mode specified by oflag. + */ +uint8_t Fat16::open(const char* fileName, uint8_t oflag) { + uint8_t dname[11]; // name formated for dir entry + int16_t empty = -1; // index of empty slot + dir_t* p; // pointer to cached dir entry + + if (!volumeInitialized_ || isOpen()) return false; + + // error if invalid name + if (!make83Name(fileName, dname)) return false; + + for (uint16_t index = 0; index < rootDirEntryCount_; index++) { + if (!(p = cacheDirEntry(index))) return false; + if (p->name[0] == DIR_NAME_FREE || p->name[0] == DIR_NAME_DELETED) { + // remember first empty slot + if (empty < 0) empty = index; + // done if no entries follow + if (p->name[0] == DIR_NAME_FREE) break; + } else if (!memcmp(dname, p->name, 11)) { + // don't open existing file if O_CREAT and O_EXCL + if ((oflag & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL)) return false; + + // open existing file + return open(index, oflag); + } + } + // error if directory is full + if (empty < 0) return false; + + // only create file if O_CREAT and O_WRITE + if ((oflag & (O_CREAT | O_WRITE)) != (O_CREAT | O_WRITE)) return false; + + if (!(p = cacheDirEntry(empty, CACHE_FOR_WRITE))) return false; + + // initialize as empty file + memset(p, 0, sizeof(dir_t)); + memcpy(p->name, dname, 11); + + // set timestamps + if (dateTime_) { + // call user function + dateTime_(&p->creationDate, &p->creationTime); + } else { + // use default date/time + p->creationDate = FAT_DEFAULT_DATE; + p->creationTime = FAT_DEFAULT_TIME; + } + p->lastAccessDate = p->creationDate; + p->lastWriteDate = p->creationDate; + p->lastWriteTime = p->creationTime; + + // insure created directory entry will be written to storage device + if (!cacheFlush()) return false; + + // open entry + return open(empty, oflag); +} +//------------------------------------------------------------------------------ +/** + * Open a file by file index. + * + * \param[in] index The root directory index of the file to be opened. See \link + * Fat16::readDir() readDir()\endlink. + * + * \param[in] oflag See \link Fat16::open(const char*, uint8_t)\endlink. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + * Reasons for failure include the FAT volume has not been initialized, + * a file is already open, \a index is invalid or is not the index of a + * file or the file cannot be opened in the access mode specified by oflag. + */ +uint8_t Fat16::open(uint16_t index, uint8_t oflag) { + if (!volumeInitialized_ || isOpen()) return false; + if ((oflag & O_TRUNC) && !(oflag & O_WRITE)) return false; + dir_t* d = cacheDirEntry(index); + // if bad file index or I/O error + if (!d) return false; + + // error if unused entry + if (d->name[0] == DIR_NAME_FREE || d->name[0] == DIR_NAME_DELETED) { + return false; + } + // error if long name, volume label or subdirectory + if ((d->attributes & (DIR_ATT_VOLUME_ID | DIR_ATT_DIRECTORY)) != 0) { + return false; + } + // don't allow write or truncate if read-only + if (d->attributes & DIR_ATT_READ_ONLY) { + if (oflag & (O_WRITE | O_TRUNC)) return false; + } + + curCluster_ = 0; + curPosition_ = 0; + dirEntryIndex_ = index; + fileSize_ = d->fileSize; + firstCluster_ = d->firstClusterLow; + flags_ = oflag & (O_ACCMODE | O_SYNC | O_APPEND); + + if (oflag & O_TRUNC ) return truncate(0); + return true; +} +//------------------------------------------------------------------------------ +/** %Print the name field of a directory entry in 8.3 format to Serial. + * + * \param[in] dir The directory structure containing the name. + * \param[in] width Blank fill name if length is less than \a width. + */ +void Fat16::printDirName(const dir_t& dir, uint8_t width) { + uint8_t w = 0; + for (uint8_t i = 0; i < 11; i++) { + if (dir.name[i] == ' ') continue; + if (i == 8) { + Serial.write('.'); + w++; + } + Serial.write(dir.name[i]); + w++; + } + if (DIR_IS_SUBDIR(&dir)) { + Serial.write('/'); + w++; + } + while (w < width) { + Serial.write(' '); + w++; + } +} +//------------------------------------------------------------------------------ +/** %Print a directory date field to Serial. + * + * Format is yyyy-mm-dd. + * + * \param[in] fatDate The date field from a directory entry. + */ +void Fat16::printFatDate(uint16_t fatDate) { + Serial.print(FAT_YEAR(fatDate)); + Serial.write('-'); + printTwoDigits(FAT_MONTH(fatDate)); + Serial.write('-'); + printTwoDigits(FAT_DAY(fatDate)); +} +//------------------------------------------------------------------------------ +/** %Print a directory time field to Serial. + * + * Format is hh:mm:ss. + * + * \param[in] fatTime The time field from a directory entry. + */ +void Fat16::printFatTime(uint16_t fatTime) { + printTwoDigits(FAT_HOUR(fatTime)); + Serial.write(':'); + printTwoDigits(FAT_MINUTE(fatTime)); + Serial.write(':'); + printTwoDigits(FAT_SECOND(fatTime)); +} + +//------------------------------------------------------------------------------ +/** %Print a value as two digits to Serial. + * + * \param[in] v Value to be printed, 0 <= \a v <= 99 + */ +void Fat16::printTwoDigits(uint8_t v) { + char str[3]; + str[0] = '0' + v/10; + str[1] = '0' + v % 10; + str[2] = 0; + Serial.print(str); +} +//------------------------------------------------------------------------------ +/** + * Read the next byte from a file. + * + * \return For success read returns the next byte in the file as an int. + * If an error occurs or end of file is reached -1 is returned. + */ +int16_t Fat16::read(void) { + uint8_t b; + return read(&b, 1) == 1 ? b : -1; +} +//------------------------------------------------------------------------------ +/** + * Read data from a file at starting at the current file position. + * + * \param[out] buf Pointer to the location that will receive the data. + * + * \param[in] nbyte Maximum number of bytes to read. + * + * \return For success read returns the number of bytes read. + * A value less than \a nbyte, including zero, may be returned + * if end of file is reached. + * If an error occurs, read returns -1. Possible errors include + * read called before a file has been opened, the file has not been opened in + * read mode, a corrupt file system, or an I/O error. + */ +int16_t Fat16::read(void* buf, uint16_t nbyte) { + // convert void pointer to uin8_t pointer + uint8_t* dst = reinterpret_cast(buf); + + // error if not open for read + if (!(flags_ & O_READ)) return -1; + + // don't read beyond end of file + if ((curPosition_ + nbyte) > fileSize_) nbyte = fileSize_ - curPosition_; + + // bytes left to read in loop + uint16_t nToRead = nbyte; + while (nToRead > 0) { + uint8_t blkOfCluster = blockOfCluster(curPosition_); + uint16_t blockOffset = cacheDataOffset(curPosition_); + if (blkOfCluster == 0 && blockOffset == 0) { + // start next cluster + if (curCluster_ == 0) { + curCluster_ = firstCluster_; + } else { + if (!fatGet(curCluster_, &curCluster_)) return -1; + } + // return error if bad cluster chain + if (curCluster_ < 2 || isEOC(curCluster_)) return -1; + } + // cache data block + if (!cacheRawBlock(dataBlockLba(curCluster_, blkOfCluster))) return -1; + + // location of data in cache + uint8_t* src = cacheBuffer_.data + blockOffset; + + // max number of byte available in block + uint16_t n = 512 - blockOffset; + + // lesser of available and amount to read + if (n > nToRead) n = nToRead; + + // copy data to caller + memcpy(dst, src, n); + + curPosition_ += n; + dst += n; + nToRead -= n; + } + return nbyte; +} +//------------------------------------------------------------------------------ +/** + * Read the next short, 8.3, directory entry. + * + * Unused entries and entries for long names are skipped. + * + * \param[out] dir Location that will receive the entry. + * + * \param[in,out] index The search starts at \a index and \a index is + * updated with the root directory index of the found directory entry. + * If the entry is a file, it may be opened by calling + * \link Fat16::open(uint16_t, uint8_t) \endlink. + * + * \param[in] skip Skip entries that have these attributes. If \a skip + * is not specified, the default is to skip the volume label and directories. + * + * \return The value one, true, is returned for success and the value zero, + * false, is returned if an error occurs or the end of the root directory is + * reached. On success, \a entry is set to the index of the found directory + * entry. + */ +uint8_t Fat16::readDir(dir_t* dir, uint16_t* index, uint8_t skip) { + dir_t* p; + for (uint16_t i = *index; ; i++) { + if (i >= rootDirEntryCount_) return false; + if (!(p = cacheDirEntry(i))) return false; + + // done if beyond last used entry + if (p->name[0] == DIR_NAME_FREE) return false; + + // skip deleted entry + if (p->name[0] == DIR_NAME_DELETED) continue; + + // skip long names + if ((p->attributes & DIR_ATT_LONG_NAME_MASK) == DIR_ATT_LONG_NAME) continue; + + // skip if attribute match + if (p->attributes & skip) continue; + + // return found index + *index = i; + break; + } + memcpy(dir, p, sizeof(dir_t)); + return true; +} +//------------------------------------------------------------------------------ +/** + * Remove a file. The directory entry and all data for the file are deleted. + * + * \note This function should not be used to delete the 8.3 version of a + * file that has a long name. For example if a file has the long name + * "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT". + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + * Reasons for failure include the file is not open for write + * or an I/O error occurred. + */ +uint8_t Fat16::remove(void) { + // error if file is not open for write + if (!(flags_ & O_WRITE)) return false; + if (firstCluster_) { + if (!freeChain(firstCluster_)) return false; + } + dir_t* d = cacheDirEntry(dirEntryIndex_, CACHE_FOR_WRITE); + if (!d) return false; + d->name[0] = DIR_NAME_DELETED; + flags_ = 0; + return cacheFlush(); +} +//------------------------------------------------------------------------------ +/** + * Remove a file. + * + * The directory entry and all data for the file are deleted. + * + * \param[in] fileName The name of the file to be removed. + * + * \note This function should not be used to delete the 8.3 version of a + * file that has a long name. For example if a file has the long name + * "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT". + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + * Reasons for failure include the file is read only, \a fileName is not found + * or an I/O error occurred. + */ +uint8_t Fat16::remove(const char* fileName) { + Fat16 file; + if (!file.open(fileName, O_WRITE)) return false; + return file.remove(); +} +//------------------------------------------------------------------------------ +/** + * Sets the file's read/write position. + * + * \param[in] pos The new position in bytes from the beginning of the file. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +uint8_t Fat16::seekSet(uint32_t pos) { + // error if file not open or seek past end of file + if (!isOpen() || pos > fileSize_) return false; + if (pos == 0) { + // set position to start of file + curCluster_ = 0; + curPosition_ = 0; + return true; + } + fat_t n = ((pos - 1) >> 9)/blocksPerCluster_; + if (pos < curPosition_ || curPosition_ == 0) { + // must follow chain from first cluster + curCluster_ = firstCluster_; + } else { + // advance from curPosition + n -= ((curPosition_ - 1) >> 9)/blocksPerCluster_; + } + while (n--) { + if (!fatGet(curCluster_, &curCluster_)) return false; + } + curPosition_ = pos; + return true; +} +//------------------------------------------------------------------------------ +/** + * The sync() call causes all modified data and directory fields + * to be written to the storage device. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + * Reasons for failure include a call to sync() before a file has been + * opened or an I/O error. + */ +uint8_t Fat16::sync(void) { + if (flags_ & F_FILE_DIR_DIRTY) { + // cache directory entry + dir_t* d = cacheDirEntry(dirEntryIndex_, CACHE_FOR_WRITE); + if (!d) return false; + + // update file size and first cluster + d->fileSize = fileSize_; + d->firstClusterLow = firstCluster_; + + // set modify time if user supplied a callback date/time function + if (dateTime_) { + dateTime_(&d->lastWriteDate, &d->lastWriteTime); + d->lastAccessDate = d->lastWriteDate; + } + flags_ &= ~F_FILE_DIR_DIRTY; + } + return cacheFlush(); +} +//------------------------------------------------------------------------------ +/** + * The timestamp() call sets a file's timestamps in its directory entry. + * + * \param[in] flags Values for \a flags are constructed by a bitwise-inclusive + * OR of flags from the following list + * + * T_ACCESS - Set the file's last access date. + * + * T_CREATE - Set the file's creation date and time. + * + * T_WRITE - Set the file's last write/modification date and time. + * + * \param[in] year Valid range 1980 - 2107 inclusive. + * + * \param[in] month Valid range 1 - 12 inclusive. + * + * \param[in] day Valid range 1 - 31 inclusive. + * + * \param[in] hour Valid range 0 - 23 inclusive. + * + * \param[in] minute Valid range 0 - 59 inclusive. + * + * \param[in] second Valid range 0 - 59 inclusive + * + * \note It is possible to set an invalid date since there is no check for + * the number of days in a month. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +uint8_t Fat16::timestamp(uint8_t flags, uint16_t year, uint8_t month, + uint8_t day, uint8_t hour, uint8_t minute, uint8_t second) { + if (!isOpen() + || year < 1980 + || year > 2107 + || month < 1 + || month > 12 + || day < 1 + || day > 31 + || hour > 23 + || minute > 59 + || second > 59) { + return false; + } + dir_t* d = cacheDirEntry(dirEntryIndex_, CACHE_FOR_WRITE); + if (!d) return false; + uint16_t dirDate = FAT_DATE(year, month, day); + uint16_t dirTime = FAT_TIME(hour, minute, second); + if (flags & T_ACCESS) { + d->lastAccessDate = dirDate; + } + if (flags & T_CREATE) { + d->creationDate = dirDate; + d->creationTime = dirTime; + // seems to be units of 1/100 second not 1/10 as Microsoft standard states + d->creationTimeTenths = second & 1 ? 100 : 0; + } + if (flags & T_WRITE) { + d->lastWriteDate = dirDate; + d->lastWriteTime = dirTime; + } + cacheSetDirty(); + return sync(); +} +//------------------------------------------------------------------------------ +/** + * Truncate a file to a specified length. The current file position + * will be maintained if it is less than or equal to \a length otherwise + * it will be set to end of file. + * + * \param[in] length The desired length for the file. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + * Reasons for failure include file is read only, file is a directory, + * \a length is greater than the current file size or an I/O error occurs. + */ +uint8_t Fat16::truncate(uint32_t length) { + // error if file is not open for write + if (!(flags_ & O_WRITE)) return false; + + if (length > fileSize_) return false; + + // fileSize and length are zero - nothing to do + if (fileSize_ == 0) return true; + uint32_t newPos = curPosition_ > length ? length : curPosition_; + if (length == 0) { + // free all clusters + if (!freeChain(firstCluster_)) return false; + curCluster_ = firstCluster_ = 0; + } else { + fat_t toFree; + if (!seekSet(length)) return false; + if (!fatGet(curCluster_, &toFree)) return false; + if (!isEOC(toFree)) { + // free extra clusters + if (!fatPut(curCluster_, FAT16EOC)) return false; + if (!freeChain(toFree)) return false; + } + } + fileSize_ = length; + flags_ |= F_FILE_DIR_DIRTY; + if (!sync()) return false; + return seekSet(newPos); +} +//------------------------------------------------------------------------------ +/** + * Write data at the current position of an open file. + * + * \note Data is moved to the cache but may not be written to the + * storage device until sync() is called. + * + * \param[in] buf Pointer to the location of the data to be written. + * + * \param[in] nbyte Number of bytes to write. + * + * \return For success write() returns the number of bytes written, always + * \a nbyte. If an error occurs, write() returns -1. Possible errors include + * write() is called before a file has been opened, the file has not been opened + * for write, device is full, a corrupt file system or an I/O error. + * + */ +int16_t Fat16::write(const void* buf, uint16_t nbyte) { + uint16_t nToWrite = nbyte; + const uint8_t* src = reinterpret_cast(buf); + + // error if file is not open for write + if (!(flags_ & O_WRITE)) goto writeErrorReturn; + + // go to end of file if O_APPEND + if ((flags_ & O_APPEND) && curPosition_ != fileSize_) { + if (!seekEnd()) goto writeErrorReturn; + } + while (nToWrite > 0) { + uint8_t blkOfCluster = blockOfCluster(curPosition_); + uint16_t blockOffset = cacheDataOffset(curPosition_); + if (blkOfCluster == 0 && blockOffset == 0) { + // start of new cluster + if (curCluster_ == 0) { + if (firstCluster_ == 0) { + // allocate first cluster of file + if (!addCluster()) goto writeErrorReturn; + } else { + curCluster_ = firstCluster_; + } + } else { + fat_t next; + if (!fatGet(curCluster_, &next)) goto writeErrorReturn; + if (isEOC(next)) { + // add cluster if at end of chain + if (!addCluster()) goto writeErrorReturn; + } else { + curCluster_ = next; + } + } + } + uint32_t lba = dataBlockLba(curCluster_, blkOfCluster); + if (blockOffset == 0 && curPosition_ >= fileSize_) { + // start of new block don't need to read into cache + if (!cacheFlush()) goto writeErrorReturn; + cacheBlockNumber_ = lba; + cacheSetDirty(); + } else { + // rewrite part of block + if (!cacheRawBlock(lba, CACHE_FOR_WRITE)) return -1; + } + uint8_t* dst = cacheBuffer_.data + blockOffset; + + // max space in block + uint16_t n = 512 - blockOffset; + + // lesser of space and amount to write + if (n > nToWrite) n = nToWrite; + + // copy data to cache + memcpy(dst, src, n); + + curPosition_ += n; + nToWrite -= n; + src += n; + } + if (curPosition_ > fileSize_) { + // update fileSize and insure sync will update dir entry + fileSize_ = curPosition_; + flags_ |= F_FILE_DIR_DIRTY; + } else if (dateTime_ && nbyte) { + // insure sync will update modified date and time + flags_ |= F_FILE_DIR_DIRTY; + } + + if (flags_ & O_SYNC) { + if (!sync()) goto writeErrorReturn; + } + return nbyte; + + writeErrorReturn: + writeError = true; + return -1; +} +//------------------------------------------------------------------------------ +/** + * Write a byte to a file. Required by the Arduino Print class. + * + * Use Fat16::writeError to check for errors. + */ +#if ARDUINO < 100 +void Fat16::write(uint8_t b) { + write(&b, 1); +} +#else // ARDUINO < 100 +size_t Fat16::write(uint8_t b) { + return write(&b, 1) == 1 ? 1 : 0; +} +#endif // ARDUINO < 100 +//------------------------------------------------------------------------------ +/** + * Write a string to a file. Used by the Arduino Print class. + * + * Use Fat16::writeError to check for errors. + */ +#if ARDUINO < 100 +void Fat16::write(const char* str) { + write(str, strlen(str)); +} +#else // ARDUINO < 100 +int16_t Fat16::write(const char* str) { + return write(str, strlen(str)); +} +#endif // ARDUINO < 100 +//------------------------------------------------------------------------------ +/** + * Write a PROGMEM string to a file. + * + * Use Fat16::writeError to check for errors. + */ +void Fat16::write_P(PGM_P str) { + for (uint8_t c; (c = pgm_read_byte(str)); str++) write(c); +} +//------------------------------------------------------------------------------ +/** + * Write a PROGMEM string followed by CR/LF to a file. + * + * Use Fat16::writeError to check for errors. + */ +void Fat16::writeln_P(PGM_P str) { + write_P(str); + println(); +} diff --git a/libraries/Robot_Control/Fat16.h b/libraries/Robot_Control/Fat16.h new file mode 100644 index 00000000000..935b9b048f7 --- /dev/null +++ b/libraries/Robot_Control/Fat16.h @@ -0,0 +1,378 @@ +/* Arduino FAT16 Library + * Copyright (C) 2008 by William Greiman + * + * This file is part of the Arduino FAT16 Library + * + * This Library is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This Library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with the Arduino Fat16 Library. If not, see + * . + */ +#ifndef Fat16_h +#define Fat16_h +/** + * \file + * Fat16 class + */ +#include +#include +#include +#include +#include +#include +//------------------------------------------------------------------------------ +/** Fat16 version YYYYMMDD */ +#define FAT16_VERSION 20111205 +//------------------------------------------------------------------------------ +// flags for ls() +/** ls() flag to print modify date */ +uint8_t const LS_DATE = 1; +/** ls() flag to print file size */ +uint8_t const LS_SIZE = 2; + +// use the gnu style oflags +/** open for reading */ +uint8_t const O_READ = 0X01; +/** same as O_READ */ +uint8_t const O_RDONLY = O_READ; +/** open for write */ +uint8_t const O_WRITE = 0X02; +/** same as O_WRITE */ +uint8_t const O_WRONLY = O_WRITE; +/** open for reading and writing */ +uint8_t const O_RDWR = O_READ | O_WRITE; +/** mask for access modes */ +uint8_t const O_ACCMODE = O_READ | O_WRITE; +/** The file offset shall be set to the end of the file prior to each write. */ +uint8_t const O_APPEND = 0X04; +/** synchronous writes - call sync() after each write */ +uint8_t const O_SYNC = 0X08; +/** create the file if nonexistent */ +uint8_t const O_CREAT = 0X10; +/** If O_CREAT and O_EXCL are set, open() shall fail if the file exists */ +uint8_t const O_EXCL = 0X20; +/** truncate the file to zero length */ +uint8_t const O_TRUNC = 0X40; + +// flags for timestamp +/** set the file's last access date */ +uint8_t const T_ACCESS = 1; +/** set the file's creation date and time */ +uint8_t const T_CREATE = 2; +/** Set the file's write date and time */ +uint8_t const T_WRITE = 4; + +/** date field for FAT directory entry */ +static inline uint16_t FAT_DATE(uint16_t year, uint8_t month, uint8_t day) { + return (year - 1980) << 9 | month << 5 | day; +} +/** year part of FAT directory date field */ +static inline uint16_t FAT_YEAR(uint16_t fatDate) { + return 1980 + (fatDate >> 9); +} +/** month part of FAT directory date field */ +static inline uint8_t FAT_MONTH(uint16_t fatDate) { + return (fatDate >> 5) & 0XF; +} +/** day part of FAT directory date field */ +static inline uint8_t FAT_DAY(uint16_t fatDate) { + return fatDate & 0X1F; +} +/** time field for FAT directory entry */ +static inline uint16_t FAT_TIME(uint8_t hour, uint8_t minute, uint8_t second) { + return hour << 11 | minute << 5 | second >> 1; +} +/** hour part of FAT directory time field */ +static inline uint8_t FAT_HOUR(uint16_t fatTime) { + return fatTime >> 11; +} +/** minute part of FAT directory time field */ +static inline uint8_t FAT_MINUTE(uint16_t fatTime) { + return(fatTime >> 5) & 0X3F; +} +/** second part of FAT directory time field */ +static inline uint8_t FAT_SECOND(uint16_t fatTime) { + return 2*(fatTime & 0X1F); +} +/** Default date for file timestamps is 1 Jan 2000 */ +uint16_t const FAT_DEFAULT_DATE = ((2000 - 1980) << 9) | (1 << 5) | 1; +/** Default time for file timestamp is 1 am */ +uint16_t const FAT_DEFAULT_TIME = (1 << 11); +//------------------------------------------------------------------------------ +/** + * \typedef fat_t + * + * \brief Type for FAT16 entry + */ +typedef uint16_t fat_t; +/** + * \union cache16_t + * + * \brief Cache buffer data type + * + */ +union cache16_t { + /** Used to access cached file data blocks. */ + uint8_t data[512]; + /** Used to access cached FAT entries. */ + fat_t fat[256]; + /** Used to access cached directory entries. */ + dir_t dir[16]; + /** Used to access a cached Master Boot Record. */ + mbr_t mbr; + /** Used to access to a cached FAT16 boot sector. */ + fbs_t fbs; +}; +//------------------------------------------------------------------------------ +/** \class Fat16 + * \brief Fat16 implements a minimal Arduino FAT16 Library + * + * Fat16 does not support subdirectories or long file names. + */ +class Fat16 : public Print { + public: + /* + * Public functions + */ + /** create with file closed */ + Fat16(void) : flags_(0) {} + /** \return The current cluster number. */ + fat_t curCluster(void) const {return curCluster_;} + uint8_t close(void); + /** \return The count of clusters in the FAT16 volume. */ + static fat_t clusterCount(void) {return clusterCount_;} + /** \return The number of 512 byte blocks in a cluster */ + static uint8_t clusterSize(void) {return blocksPerCluster_;} + /** \return The current file position. */ + uint32_t curPosition(void) const {return curPosition_;} + /** + * Set the date/time callback function + * + * \param[in] dateTime The user's callback function. The callback + * function is of the form: + * + * \code + * void dateTime(uint16_t* date, uint16_t* time) { + * uint16_t year; + * uint8_t month, day, hour, minute, second; + * + * // User gets date and time from GPS or real-time clock here + * + * // return date using FAT_DATE macro to format fields + * *date = FAT_DATE(year, month, day); + * + * // return time using FAT_TIME macro to format fields + * *time = FAT_TIME(hour, minute, second); + * } + * \endcode + * + * Sets the function that is called when a file is created or when + * a file's directory entry is modified by sync(). All timestamps, + * access, creation, and modify, are set when a file is created. + * sync() maintains the last access date and last modify date/time. + * + * See the timestamp() function. + */ + static void dateTimeCallback( + void (*dateTime)(uint16_t* date, uint16_t* time)) { + dateTime_ = dateTime; + } + /** + * Cancel the date/time callback function. + */ + static void dateTimeCallbackCancel(void) {dateTime_ = NULL;} + uint8_t dirEntry(dir_t* dir); + + /** \return The file's size in bytes. */ + uint32_t fileSize(void) const {return fileSize_;} + static uint8_t init(SdCard* dev, uint8_t part); + /** + * Initialize a FAT16 volume. + * + * First try partition 1 then try super floppy format. + * + * \param[in] dev The SdCard where the volume is located. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. reasons for + * failure include not finding a valid FAT16 file system, a call + * to init() after a volume has been successful initialized or + * an I/O error. + * + */ + static uint8_t init(SdCard* dev) { + return init(dev, 1) ? true : init(dev, 0); + } + /** + * Checks the file's open/closed status for this instance of Fat16. + * \return The value true if a file is open otherwise false; + */ + uint8_t isOpen(void) const {return (flags_ & O_ACCMODE) != 0;} + static void ls(uint8_t flags = 0); + uint8_t open(const char* fileName, uint8_t oflag); + uint8_t open(uint16_t entry, uint8_t oflag); + static void printDirName(const dir_t& dir, uint8_t width); + static void printFatDate(uint16_t fatDate); + static void printFatTime(uint16_t fatTime); + static void printTwoDigits(uint8_t v); + int16_t read(void); + int16_t read(void* buf, uint16_t nbyte); + static uint8_t readDir(dir_t* dir, uint16_t* index, + uint8_t skip = (DIR_ATT_VOLUME_ID | DIR_ATT_DIRECTORY)); + + uint8_t remove(void); + static uint8_t remove(const char* fileName); + /** Sets the file's current position to zero. */ + void rewind(void) {curPosition_ = curCluster_ = 0;} + /** \return The number of entries in the root directory. */ + static uint16_t rootDirEntryCount(void) {return rootDirEntryCount_;} + /** Seek to current position plus \a pos bytes. See Fat16::seekSet(). */ + uint8_t seekCur(uint32_t pos) {return seekSet(curPosition_ + pos);} + /** Seek to end of file. See Fat16::seekSet(). */ + uint8_t seekEnd(void) {return seekSet(fileSize_);} + uint8_t seekSet(uint32_t pos); + uint8_t sync(void); + uint8_t timestamp(uint8_t flag, uint16_t year, uint8_t month, uint8_t day, + uint8_t hour, uint8_t minute, uint8_t second); + uint8_t truncate(uint32_t size); + /** Fat16::writeError is set to true if an error occurs during a write(). + * Set Fat16::writeError to false before calling print() and/or write() and check + * for true after calls to write() and/or print(). + */ + bool writeError; + int16_t write(const void *buf, uint16_t nbyte); +#if ARDUINO < 100 + void write(uint8_t b); + void write(const char* str); +#else // ARDUINO < 100 + size_t write(uint8_t b); + int16_t write(const char* str); +#endif // ARDUINO < 100 + void write_P(PGM_P str); + void writeln_P(PGM_P str); +//------------------------------------------------------------------------------ +#if FAT16_DEBUG_SUPPORT + /** For debug only. Do not use in applications. */ + static cache16_t* dbgBufAdd(void) {return &cacheBuffer_;} + /** For debug only. Do not use in applications. */ + static void dbgSetDev(SdCard* dev) {rawDev_ = dev;} + /** For debug only. Do not use in applications. */ + static uint8_t* dbgCacheBlock(uint32_t blockNumber) { + return cacheRawBlock(blockNumber) ? cacheBuffer_.data : 0; } + /** For debug only. Do not use in applications. */ + static dir_t* dbgCacheDir(uint16_t index) { + return cacheDirEntry(index);} +#endif // FAT16_DEBUG_SUPPORT +//------------------------------------------------------------------------------ +#if ALLOW_DEPRECATED_FUNCTIONS +// Deprecated functions - suppress cpplint messages with NOLINT comment + public: + /** + * Deprecated - Use: + * static void Fat16::dateTimeCallback( + * void (*dateTime)(uint16_t* date, uint16_t* time)); + */ + static void dateTimeCallback( + void (*dateTime)(uint16_t& date, uint16_t& time)) { // NOLINT + oldDateTime_ = dateTime; + dateTime_ = dateTime ? oldToNew : 0; + } + /** Deprecated - Use: uint8_t Fat16::dirEntry(dir_t* dir); */ + uint8_t dirEntry(dir_t& dir) { // NOLINT + return dirEntry(&dir); + } + /** Deprecated - Use: static uint8_t Fat16::init(SdCard *dev); */ + static uint8_t init(SdCard& dev) {return init(&dev);} // NOLINT + + /** Deprecated - Use: static uint8_t Fat16::init(SdCard *dev, uint8_t part) */ + static uint8_t init(SdCard& dev, uint8_t part) { // NOLINT + return init(&dev, part); + } + /** + * Deprecated - Use: + * uint8_t Fat16::readDir(dir_t* dir, uint16_t* index, uint8_t skip); + */ + static uint8_t readDir(dir_t& dir, uint16_t& index, // NOLINT + uint8_t skip = (DIR_ATT_VOLUME_ID | DIR_ATT_DIRECTORY)) { + return readDir(&dir, &index, skip); + } +//------------------------------------------------------------------------------ + private: + static void (*oldDateTime_)(uint16_t& date, uint16_t& time); // NOLINT + static void oldToNew(uint16_t *date, uint16_t *time) { + uint16_t d; + uint16_t t; + oldDateTime_(d, t); + *date = d; + *time = t; + } +#endif // ALLOW_DEPRECATED_FUNCTIONS +//------------------------------------------------------------------------------ + private: + // Volume info + static uint8_t volumeInitialized_; // true if volume has been initialized + static uint8_t fatCount_; // number of FATs + static uint8_t blocksPerCluster_; // must be power of 2 + static uint16_t rootDirEntryCount_; // should be 512 for FAT16 + static fat_t blocksPerFat_; // number of blocks in one FAT + static fat_t clusterCount_; // total clusters in volume + static uint32_t fatStartBlock_; // start of first FAT + static uint32_t rootDirStartBlock_; // start of root dir + static uint32_t dataStartBlock_; // start of data clusters + + // block cache + static uint8_t const CACHE_FOR_READ = 0; // cache a block for read + static uint8_t const CACHE_FOR_WRITE = 1; // cache a block and set dirty + static SdCard *rawDev_; // Device + static cache16_t cacheBuffer_; // 512 byte cache for raw blocks + static uint32_t cacheBlockNumber_; // Logical number of block in the cache + static uint8_t cacheDirty_; // cacheFlush() will write block if true + static uint32_t cacheMirrorBlock_; // mirror block for second FAT + + // callback function for date/time + static void (*dateTime_)(uint16_t* date, uint16_t* time); + + // define fields in flags_ + static uint8_t const F_OFLAG = O_ACCMODE | O_APPEND | O_SYNC; + static uint8_t const F_FILE_DIR_DIRTY = 0X80; // require sync directory entry + + uint8_t flags_; // see above for bit definitions + int16_t dirEntryIndex_; // index of directory entry for open file + fat_t firstCluster_; // first cluster of file + uint32_t fileSize_; // fileSize + fat_t curCluster_; // current cluster + uint32_t curPosition_; // current byte offset + + // private functions for cache + static uint8_t blockOfCluster(uint32_t position) { + // depends on blocks per cluster being power of two + return (position >> 9) & (blocksPerCluster_ - 1); + } + static uint16_t cacheDataOffset(uint32_t position) {return position & 0X1FF;} + static dir_t* cacheDirEntry(uint16_t index, uint8_t action = 0); + static uint8_t cacheRawBlock(uint32_t blockNumber, uint8_t action = 0); + static uint8_t cacheFlush(void); + static void cacheSetDirty(void) {cacheDirty_ |= CACHE_FOR_WRITE;} + static uint32_t dataBlockLba(fat_t cluster, uint8_t blockOfCluster) { + return dataStartBlock_ + (uint32_t)(cluster - 2) * blocksPerCluster_ + + blockOfCluster; + } + static uint8_t fatGet(fat_t cluster, fat_t* value); + static uint8_t fatPut(fat_t cluster, fat_t value); + // end of chain test + static uint8_t isEOC(fat_t cluster) {return cluster >= 0XFFF8;} + // allocate a cluster to a file + uint8_t addCluster(void); + // free a cluster chain + uint8_t freeChain(fat_t cluster); +}; +#endif // Fat16_h diff --git a/libraries/Robot_Control/Fat16Config.h b/libraries/Robot_Control/Fat16Config.h new file mode 100644 index 00000000000..d598b56093e --- /dev/null +++ b/libraries/Robot_Control/Fat16Config.h @@ -0,0 +1,38 @@ +/* Arduino FAT16 Library + * Copyright (C) 2008 by William Greiman + * + * This file is part of the Arduino FAT16 Library + * + * This Library is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This Library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with the Arduino Fat16 Library. If not, see + * . + */ + /** + * \file + * Configuration file + */ +#ifndef Fat16Config_h +#define Fat16Config_h +/** + * Allow use of deprecated functions if non-zero + */ +#define ALLOW_DEPRECATED_FUNCTIONS 1 +/** + * SdCard::writeBlock will protect block zero if set non-zero + */ +#define SD_PROTECT_BLOCK_ZERO 1 +/** + * Set non-zero to allow access to Fat16 internals by cardInfo debug sketch + */ +#define FAT16_DEBUG_SUPPORT 1 +#endif // Fat16Config_h diff --git a/libraries/Robot_Control/Fat16mainpage.h b/libraries/Robot_Control/Fat16mainpage.h new file mode 100644 index 00000000000..2c4f773b3c7 --- /dev/null +++ b/libraries/Robot_Control/Fat16mainpage.h @@ -0,0 +1,208 @@ +/* Arduino FAT16 Library + * Copyright (C) 2008 by William Greiman + * + * This file is part of the Arduino FAT16 Library + * + * This Library is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This Library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with the Arduino Fat16 Library. If not, see + * . + */ + +/** +\mainpage Arduino Fat16 Library +
Copyright © 2008 by William Greiman +
+ +\section Intro Introduction +The Arduino Fat16 Library is a minimal implementation of the FAT16 file system +on standard SD flash memory cards. Fat16 supports read, write, file +creation, deletion, and truncation. + +The Fat16 class only supports access to files in the root directory and only +supports short 8.3 names. Directory time and date fields for creation +and modification can be maintained by providing a date/time callback +function \link Fat16::dateTimeCallback() dateTimeCallback()\endlink +or calling \link Fat16::timestamp() timestamp()\endlink. + +Fat16 was designed to use the Arduino Print class which +allows files to be written with \link Print::print() print() \endlink and +\link Print::println() println()\endlink. + +\section comment Bugs and Comments + +If you wish to report bugs or have comments, send email to fat16lib@sbcglobal.net. + + +\section SDcard SD Cards + +Arduinos access SD cards using the cards SPI protocol. PCs, Macs, and +most consumer devices use the 4-bit parallel SD protocol. A card that +functions well on A PC or Mac may not work well on the Arduino. + +Most cards have good SPI read performance but cards vary widely in SPI +write performance. Write performance is limited by how efficiently the +card manages internal erase/remapping operations. The Arduino cannot +optimize writes to reduce erase operations because of its limit RAM. + +SanDisk cards generally have good write performance. They seem to have +more internal RAM buffering than other cards and therefore can limit +the number of flash erase operations that the Arduino forces due to its +limited RAM. + +Some Dane-Elec cards have a write speed that is only 20% as fast as +a good SanDisk card. + + +\section Hardware Hardware Configuration +Fat16 was developed using an Adafruit Industries + GPS Shield. + +The hardware interface to the SD card should not use a resistor based level +shifter. SdCard::init() sets the SPI bus frequency to 8 MHz which results in +signal rise times that are too slow for the edge detectors in many newer SD card +controllers when resistor voltage dividers are used. + +The 5 to 3.3 V level shifter for 5 V arduinos should be IC based like the +74HC4050N based circuit shown in the file SdLevel.png. The Adafruit Wave Shield +uses a 74AHC125N. Gravitech sells SD and MicroSD Card Adapters based on the +74LCX245. + +If you are using a resistor based level shifter and are having problems try +setting the SPI bus frequency to 4 MHz. This can be done by using +card.init(true) to initialize the SD card. + + +\section Fat16Class Fat16 Usage + +The class Fat16 is a minimal implementation of FAT16 on standard SD cards. +High Capacity SD cards, SDHC, are not supported. It should work on all +standard cards from 8MB to 2GB formatted with a FAT16 file system. + +\note + The Arduino Print class uses character +at a time writes so it was necessary to use a \link Fat16::sync() sync() \endlink +function to control when data is written to the SD card. + +\par +An application which writes to a file using \link Print::print() print()\endlink, +\link Print::println() println() \endlink +or \link Fat16::write write() \endlink must call \link Fat16::sync() sync() \endlink +at the appropriate time to force data and directory information to be written +to the SD Card. Data and directory information are also written to the SD card +when \link Fat16::close() close() \endlink is called. + +\par +Applications must use care calling \link Fat16::sync() sync() \endlink +since 2048 bytes of I/O is required to update file and +directory information. This includes writing the current data block, reading +the block that contains the directory entry for update, writing the directory +block back and reading back the current data block. + +Fat16 only supports access to files in the root directory and only supports +short 8.3 names. + +It is possible to open a file with two or more instances of Fat16. A file may +be corrupted if data is written to the file by more than one instance of Fat16. + +Short names are limited to 8 characters followed by an optional period (.) +and extension of up to 3 characters. The characters may be any combination +of letters and digits. The following special characters are also allowed: + +$ % ' - _ @ ~ ` ! ( ) { } ^ # & + +Short names are always converted to upper case and their original case +value is lost. + +Fat16 uses a slightly restricted form of short names. +Only printable ASCII characters are supported. No characters with code point +values greater than 127 are allowed. Space is not allowed even though space +was allowed in the API of early versions of DOS. + +Fat16 has been optimized for The Arduino ATmega168. Minimizing RAM use is the +highest priority goal followed by flash use and finally performance. +Most SD cards only support 512 byte block write operations so a 512 byte +cache buffer is used by Fat16. This is the main use of RAM. A small +amount of RAM is used to store key volume and file information. +Flash memory usage can be controlled by selecting options in Fat16Config.h. + +\section HowTo How to format SD Cards as FAT16 Volumes + +Microsoft operating systems support removable media formatted with a +Master Boot Record, MBR, or formatted as a super floppy with a FAT Boot Sector +in block zero. + +Microsoft operating systems expect MBR formatted removable media +to have only one partition. The first partition should be used. + +Microsoft operating systems do not support partitioning SD flash cards. +If you erase an SD card with a program like KillDisk, Most versions of +Windows will format the card as a super floppy. + +The best way to restore an SD card's MBR is to use SDFormatter +which can be downloaded from: + +http://www.sdcard.org/consumers/formatter/ + +SDFormatter does not have an option for FAT type so it may format +small cards as FAT12. + +After the MBR is restored by SDFormatter you may need to reformat small +cards that have been formatted FAT12 to force the volume type to be FAT16. + +The FAT type, FAT12, FAT16, or FAT32, is determined by the count +of clusters on the volume and nothing else. + +Microsoft published the following code for determining FAT type: + +\code +if (CountOfClusters < 4085) { + // Volume is FAT12 +} +else if (CountOfClusters < 65525) { + // Volume is FAT16 +} +else { + // Volume is FAT32 +} + +\endcode +If you format a FAT volume with an OS utility , choose a cluster size that +will result in: + +4084 < CountOfClusters && CountOfClusters < 65525 + +The volume will then be FAT16. + +If you are formatting an SD card on OS X or Linux, be sure to use the first +partition. Format this partition with a cluster count in above range. + +\section References References + +The Arduino site: + +http://www.arduino.cc/ + +For more information about FAT file systems see: + +http://www.microsoft.com/whdc/system/platform/firmware/fatgen.mspx + +For information about using SD cards as SPI devices see: + +http://www.sdcard.org/developers/tech/sdcard/pls/Simplified_Physical_Layer_Spec.pdf + +The ATmega328 datasheet: + +http://www.atmel.com/dyn/resources/prod_documents/doc8161.pdf + + + */ \ No newline at end of file diff --git a/libraries/Robot_Control/Fat16util.h b/libraries/Robot_Control/Fat16util.h new file mode 100644 index 00000000000..1fea068ecc6 --- /dev/null +++ b/libraries/Robot_Control/Fat16util.h @@ -0,0 +1,74 @@ +#ifndef Fat16util_h +#define Fat16util_h +/* Arduino FAT16 Library + * Copyright (C) 2008 by William Greiman + * + * This file is part of the Arduino FAT16 Library + * + * This Library is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This Library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with the Arduino Fat16 Library. If not, see + * . + */ +/** + * \file + * Useful utility functions. + */ +#if ARDUINO < 100 +#include +#else // ARDUINO +#include +#endif // ARDUINO +#include +/** Store and print a string in flash memory.*/ +#define PgmPrint(x) SerialPrint_P(PSTR(x)) +/** Store and print a string in flash memory followed by a CR/LF.*/ +#define PgmPrintln(x) SerialPrintln_P(PSTR(x)) +/** Defined so doxygen works for function definitions. */ +#define NOINLINE __attribute__((noinline)) +//------------------------------------------------------------------------------ +/** Return the number of bytes currently free in RAM. */ +static int FreeRam(void) { + extern int __bss_end; + extern int* __brkval; + int free_memory; + if (reinterpret_cast(__brkval) == 0) { + // if no heap use from end of bss section + free_memory = reinterpret_cast(&free_memory) + - reinterpret_cast(&__bss_end); + } else { + // use from top of stack to heap + free_memory = reinterpret_cast(&free_memory) + - reinterpret_cast(__brkval); + } + return free_memory; +} +//------------------------------------------------------------------------------ +/** + * %Print a string in flash memory to the serial port. + * + * \param[in] str Pointer to string stored in flash memory. + */ +static NOINLINE void SerialPrint_P(PGM_P str) { + for (uint8_t c; (c = pgm_read_byte(str)); str++) Serial.write(c); +} +//------------------------------------------------------------------------------ +/** + * %Print a string in flash memory followed by a CR/LF. + * + * \param[in] str Pointer to string stored in flash memory. + */ +static NOINLINE void SerialPrintln_P(PGM_P str) { + SerialPrint_P(str); + Serial.println(); +} +#endif // #define Fat16util_h diff --git a/libraries/Robot_Control/FatStructs.h b/libraries/Robot_Control/FatStructs.h new file mode 100644 index 00000000000..431bf307712 --- /dev/null +++ b/libraries/Robot_Control/FatStructs.h @@ -0,0 +1,418 @@ +/* Arduino Fat16 Library + * Copyright (C) 2009 by William Greiman + * + * This file is part of the Arduino Fat16 Library + * + * This Library is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This Library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with the Arduino Fat16 Library. If not, see + * . + */ +#ifndef FatStructs_h +#define FatStructs_h +/** + * \file + * FAT file structures + */ +/* + * mostly from Microsoft document fatgen103.doc + * http://www.microsoft.com/whdc/system/platform/firmware/fatgen.mspx + */ +//------------------------------------------------------------------------------ +/** Value for byte 510 of boot block or MBR */ +uint8_t const BOOTSIG0 = 0X55; +/** Value for byte 511 of boot block or MBR */ +uint8_t const BOOTSIG1 = 0XAA; +//------------------------------------------------------------------------------ +/** + * \struct partitionTable + * \brief MBR partition table entry + * + * A partition table entry for a MBR formatted storage device. + * The MBR partition table has four entries. + */ +struct partitionTable { + /** + * Boot Indicator . Indicates whether the volume is the active + * partition. Legal values include: 0X00. Do not use for booting. + * 0X80 Active partition. + */ + uint8_t boot; + /** + * Head part of Cylinder-head-sector address of the first block in + * the partition. Legal values are 0-255. Only used in old PC BIOS. + */ + uint8_t beginHead; + /** + * Sector part of Cylinder-head-sector address of the first block in + * the partition. Legal values are 1-63. Only used in old PC BIOS. + */ + unsigned beginSector : 6; + /** High bits cylinder for first block in partition. */ + unsigned beginCylinderHigh : 2; + /** + * Combine beginCylinderLow with beginCylinderHigh. Legal values + * are 0-1023. Only used in old PC BIOS. + */ + uint8_t beginCylinderLow; + /** + * Partition type. See defines that begin with PART_TYPE_ for + * some Microsoft partition types. + */ + uint8_t type; + /** + * head part of cylinder-head-sector address of the last sector in the + * partition. Legal values are 0-255. Only used in old PC BIOS. + */ + uint8_t endHead; + /** + * Sector part of cylinder-head-sector address of the last sector in + * the partition. Legal values are 1-63. Only used in old PC BIOS. + */ + unsigned endSector : 6; + /** High bits of end cylinder */ + unsigned endCylinderHigh : 2; + /** + * Combine endCylinderLow with endCylinderHigh. Legal values + * are 0-1023. Only used in old PC BIOS. + */ + uint8_t endCylinderLow; + /** Logical block address of the first block in the partition. */ + uint32_t firstSector; + /** Length of the partition, in blocks. */ + uint32_t totalSectors; +}; +/** Type name for partitionTable */ +typedef struct partitionTable part_t; +//------------------------------------------------------------------------------ +/** + * \struct masterBootRecord + * + * \brief Master Boot Record + * + * The first block of a storage device that is formatted with a MBR. + */ +struct masterBootRecord { + /** Code Area for master boot program. */ + uint8_t codeArea[440]; + /** Optional WindowsNT disk signature. May contain more boot code. */ + uint32_t diskSignature; + /** Usually zero but may be more boot code. */ + uint16_t usuallyZero; + /** Partition tables. */ + part_t part[4]; + /** First MBR signature byte. Must be 0X55 */ + uint8_t mbrSig0; + /** Second MBR signature byte. Must be 0XAA */ + uint8_t mbrSig1; +}; +/** Type name for masterBootRecord */ +typedef struct masterBootRecord mbr_t; +//------------------------------------------------------------------------------ +/** + * \struct biosParmBlock + * + * \brief BIOS parameter block + * + * The BIOS parameter block describes the physical layout of a FAT volume. + */ +struct biosParmBlock { + /** + * Count of bytes per sector. This value may take on only the + * following values: 512, 1024, 2048 or 4096 + */ + uint16_t bytesPerSector; + /** + * Number of sectors per allocation unit. This value must be a + * power of 2 that is greater than 0. The legal values are + * 1, 2, 4, 8, 16, 32, 64, and 128. + */ + uint8_t sectorsPerCluster; + /** + * Number of sectors before the first FAT. + * This value must not be zero. + */ + uint16_t reservedSectorCount; + /** The count of FAT data structures on the volume. This field should + * always contain the value 2 for any FAT volume of any type. + */ + uint8_t fatCount; + /** + * For FAT12 and FAT16 volumes, this field contains the count of + * 32-byte directory entries in the root directory. For FAT32 volumes, + * this field must be set to 0. For FAT12 and FAT16 volumes, this + * value should always specify a count that when multiplied by 32 + * results in a multiple of bytesPerSector. FAT16 volumes should + * use the value 512. + */ + uint16_t rootDirEntryCount; + /** + * This field is the old 16-bit total count of sectors on the volume. + * This count includes the count of all sectors in all four regions + * of the volume. This field can be 0; if it is 0, then totalSectors32 + * must be non-zero. For FAT32 volumes, this field must be 0. For + * FAT12 and FAT16 volumes, this field contains the sector count, and + * totalSectors32 is 0 if the total sector count fits + * (is less than 0x10000). + */ + uint16_t totalSectors16; + /** + * This dates back to the old MS-DOS 1.x media determination and is + * no longer usually used for anything. 0xF8 is the standard value + * for fixed (non-removable) media. For removable media, 0xF0 is + * frequently used. Legal values are 0xF0 or 0xF8-0xFF. + */ + uint8_t mediaType; + /** + * Count of sectors occupied by one FAT on FAT12/FAT16 volumes. + * On FAT32 volumes this field must be 0, and sectorsPerFat32 + * contains the FAT size count. + */ + uint16_t sectorsPerFat16; + /** Sectors per track for interrupt 0x13. Not used otherwise. */ + uint16_t sectorsPerTrtack; + /** Number of heads for interrupt 0x13. Not used otherwise. */ + uint16_t headCount; + /** + * Count of hidden sectors preceding the partition that contains this + * FAT volume. This field is generally only relevant for media + * visible on interrupt 0x13. + */ + uint32_t hidddenSectors; + /** + * This field is the new 32-bit total count of sectors on the volume. + * This count includes the count of all sectors in all four regions + * of the volume. This field can be 0; if it is 0, then + * totalSectors16 must be non-zero. + */ + uint32_t totalSectors32; + /** + * Count of sectors occupied by one FAT on FAT32 volumes. + */ + uint32_t sectorsPerFat32; + /** + * This field is only defined for FAT32 media and does not exist on + * FAT12 and FAT16 media. + * Bits 0-3 -- Zero-based number of active FAT. + * Only valid if mirroring is disabled. + * Bits 4-6 -- Reserved. + * Bit 7 -- 0 means the FAT is mirrored at runtime into all FATs. + * -- 1 means only one FAT is active; it is the one referenced in bits 0-3. + * Bits 8-15 -- Reserved. + */ + uint16_t fat32Flags; + /** + * FAT32 version. High byte is major revision number. + * Low byte is minor revision number. Only 0.0 define. + */ + uint16_t fat32Version; + /** + * Cluster number of the first cluster of the root directory for FAT32. + * This usually 2 but not required to be 2. + */ + uint32_t fat32RootCluster; + /** + * Sector number of FSINFO structure in the reserved area of the + * FAT32 volume. Usually 1. + */ + uint16_t fat32FSInfo; + /** + * If non-zero, indicates the sector number in the reserved area + * of the volume of a copy of the boot record. Usually 6. + * No value other than 6 is recommended. + */ + uint16_t fat32BackBootBlock; + /** + * Reserved for future expansion. Code that formats FAT32 volumes + * should always set all of the bytes of this field to 0. + */ + uint8_t fat32Reserved[12]; +}; +/** Type name for biosParmBlock */ +typedef struct biosParmBlock bpb_t; +//------------------------------------------------------------------------------ +/** + * \struct fat32BootSector + * + * \brief Boot sector for a FAT16 or FAT32 volume. + * + */ +struct fat32BootSector { + /** X86 jmp to boot program */ + uint8_t jmpToBootCode[3]; + /** informational only - don't depend on it */ + char oemName[8]; + /** BIOS Parameter Block */ + bpb_t bpb; + /** for int0x13 use value 0X80 for hard drive */ + uint8_t driveNumber; + /** used by Windows NT - should be zero for FAT */ + uint8_t reserved1; + /** 0X29 if next three fields are valid */ + uint8_t bootSignature; + /** usually generated by combining date and time */ + uint32_t volumeSerialNumber; + /** should match volume label in root dir */ + char volumeLabel[11]; + /** informational only - don't depend on it */ + char fileSystemType[8]; + /** X86 boot code */ + uint8_t bootCode[420]; + /** must be 0X55 */ + uint8_t bootSectorSig0; + /** must be 0XAA */ + uint8_t bootSectorSig1; +}; +//------------------------------------------------------------------------------ +// End Of Chain values for FAT entries +/** FAT16 end of chain value used by Microsoft. */ +uint16_t const FAT16EOC = 0XFFFF; +/** Minimum value for FAT16 EOC. Use to test for EOC. */ +uint16_t const FAT16EOC_MIN = 0XFFF8; +/** FAT32 end of chain value used by Microsoft. */ +uint32_t const FAT32EOC = 0X0FFFFFFF; +/** Minimum value for FAT32 EOC. Use to test for EOC. */ +uint32_t const FAT32EOC_MIN = 0X0FFFFFF8; +/** Mask a for FAT32 entry. Entries are 28 bits. */ +uint32_t const FAT32MASK = 0X0FFFFFFF; + +/** Type name for fat32BootSector */ +typedef struct fat32BootSector fbs_t; +//------------------------------------------------------------------------------ +/** + * \struct directoryEntry + * \brief FAT short directory entry + * + * Short means short 8.3 name, not the entry size. + * + * Date Format. A FAT directory entry date stamp is a 16-bit field that is + * basically a date relative to the MS-DOS epoch of 01/01/1980. Here is the + * format (bit 0 is the LSB of the 16-bit word, bit 15 is the MSB of the + * 16-bit word): + * + * Bits 9-15: Count of years from 1980, valid value range 0-127 + * inclusive (1980-2107). + * + * Bits 5-8: Month of year, 1 = January, valid value range 1-12 inclusive. + * + * Bits 0-4: Day of month, valid value range 1-31 inclusive. + * + * Time Format. A FAT directory entry time stamp is a 16-bit field that has + * a granularity of 2 seconds. Here is the format (bit 0 is the LSB of the + * 16-bit word, bit 15 is the MSB of the 16-bit word). + * + * Bits 11-15: Hours, valid value range 0-23 inclusive. + * + * Bits 5-10: Minutes, valid value range 0-59 inclusive. + * + * Bits 0-4: 2-second count, valid value range 0-29 inclusive (0 - 58 seconds). + * + * The valid time range is from Midnight 00:00:00 to 23:59:58. + */ +struct directoryEntry { + /** + * Short 8.3 name. + * The first eight bytes contain the file name with blank fill. + * The last three bytes contain the file extension with blank fill. + */ + uint8_t name[11]; + /** Entry attributes. + * + * The upper two bits of the attribute byte are reserved and should + * always be set to 0 when a file is created and never modified or + * looked at after that. See defines that begin with DIR_ATT_. + */ + uint8_t attributes; + /** + * Reserved for use by Windows NT. Set value to 0 when a file is + * created and never modify or look at it after that. + */ + uint8_t reservedNT; + /** + * The granularity of the seconds part of creationTime is 2 seconds + * so this field is a count of tenths of a second and its valid + * value range is 0-199 inclusive. (WHG note - seems to be hundredths) + */ + uint8_t creationTimeTenths; + /** Time file was created. */ + uint16_t creationTime; + /** Date file was created. */ + uint16_t creationDate; + /** + * Last access date. Note that there is no last access time, only + * a date. This is the date of last read or write. In the case of + * a write, this should be set to the same date as lastWriteDate. + */ + uint16_t lastAccessDate; + /** + * High word of this entry's first cluster number (always 0 for a + * FAT12 or FAT16 volume). + */ + uint16_t firstClusterHigh; + /** Time of last write. File creation is considered a write. */ + uint16_t lastWriteTime; + /** Date of last write. File creation is considered a write. */ + uint16_t lastWriteDate; + /** Low word of this entry's first cluster number. */ + uint16_t firstClusterLow; + /** 32-bit unsigned holding this file's size in bytes. */ + uint32_t fileSize; +}; +//------------------------------------------------------------------------------ +// Definitions for directory entries +// +/** Type name for directoryEntry */ +typedef struct directoryEntry dir_t; +/** escape for name[0] = 0XE5 */ +uint8_t const DIR_NAME_0XE5 = 0X05; +/** name[0] value for entry that is free after being "deleted" */ +uint8_t const DIR_NAME_DELETED = 0XE5; +/** name[0] value for entry that is free and no allocated entries follow */ +uint8_t const DIR_NAME_FREE = 0X00; +/** file is read-only */ +uint8_t const DIR_ATT_READ_ONLY = 0X01; +/** File should hidden in directory listings */ +uint8_t const DIR_ATT_HIDDEN = 0X02; +/** Entry is for a system file */ +uint8_t const DIR_ATT_SYSTEM = 0X04; +/** Directory entry contains the volume label */ +uint8_t const DIR_ATT_VOLUME_ID = 0X08; +/** Entry is for a directory */ +uint8_t const DIR_ATT_DIRECTORY = 0X10; +/** Old DOS archive bit for backup support */ +uint8_t const DIR_ATT_ARCHIVE = 0X20; +/** Test value for long name entry. Test is + (d->attributes & DIR_ATT_LONG_NAME_MASK) == DIR_ATT_LONG_NAME. */ +uint8_t const DIR_ATT_LONG_NAME = 0X0F; +/** Test mask for long name entry */ +uint8_t const DIR_ATT_LONG_NAME_MASK = 0X3F; +/** defined attribute bits */ +uint8_t const DIR_ATT_DEFINED_BITS = 0X3F; +/** Directory entry is part of a long name */ +static inline uint8_t DIR_IS_LONG_NAME(const dir_t* dir) { + return (dir->attributes & DIR_ATT_LONG_NAME_MASK) == DIR_ATT_LONG_NAME; +} +/** Mask for file/subdirectory tests */ +uint8_t const DIR_ATT_FILE_TYPE_MASK = (DIR_ATT_VOLUME_ID | DIR_ATT_DIRECTORY); +/** Directory entry is for a file */ +static inline uint8_t DIR_IS_FILE(const dir_t* dir) { + return (dir->attributes & DIR_ATT_FILE_TYPE_MASK) == 0; +} +/** Directory entry is for a subdirectory */ +static inline uint8_t DIR_IS_SUBDIR(const dir_t* dir) { + return (dir->attributes & DIR_ATT_FILE_TYPE_MASK) == DIR_ATT_DIRECTORY; +} +/** Directory entry is for a file or subdirectory */ +static inline uint8_t DIR_IS_FILE_OR_SUBDIR(const dir_t* dir) { + return (dir->attributes & DIR_ATT_VOLUME_ID) == 0; +} +#endif // FatStructs_h diff --git a/libraries/Robot_Control/Melody.cpp b/libraries/Robot_Control/Melody.cpp new file mode 100644 index 00000000000..0341c555ef2 --- /dev/null +++ b/libraries/Robot_Control/Melody.cpp @@ -0,0 +1,100 @@ +#include "ArduinoRobot.h" +#include "SquawkSD.h" +#include "Fat16.h" + + + +SQUAWK_CONSTRUCT_ISR(SQUAWK_PWM_PIN5); + + +void RobotControl::beginSpeaker(uint16_t frequency){ + SquawkSynth::begin(frequency); + SquawkSynth::play(); + osc[2].vol = 0x7F; +} + +void RobotControl::playNote(byte period, word length, char modifier) { + // Modifier . makes note length 2/3 + if(modifier == '.') length = (length * 2) / 3; + // Set up the play frequency, 352800 is [sample_rate]=44100 * [tuning]=8.0 + osc[2].freq = 352800 / period; + // Delay, silence, delay + delay(length); + osc[2].freq = 0; + delay(length); +} + +void RobotControl::playMelody(char* script){ + // Find length of play string + word length = strlen(script); + // Set the default note time + word time = 500; + // Loop through each character in the play string + for(int n = 0; n < length; n++) { + // Fetch the character AFTER the current one - it may contain a modifier + char modifier = script[n + 1]; + // Fetch the current character and branch accordingly + switch(script[n]) { + // Notes + case 'c': playNote(214, time, modifier); break; // Play a C + case 'C': playNote(202, time, modifier); break; // Play a C# + case 'd': playNote(190, time, modifier); break; // Play a D + case 'D': playNote(180, time, modifier); break; // Play a D# + case 'e': playNote(170, time, modifier); break; // Play an F + case 'f': playNote(160, time, modifier); break; // Play an F + case 'F': playNote(151, time, modifier); break; // Play an F# + case 'g': playNote(143, time, modifier); break; // Play a G + case 'G': playNote(135, time, modifier); break; // Play a G# + case 'a': playNote(127, time, modifier); break; // Play an A + case 'A': playNote(120, time, modifier); break; // Play an A# + case 'b': playNote(113, time, modifier); break; // Play a B + // Delay + case '-': playNote(0, time, modifier); break; // Play a quiet note + // Note lengths + case '1': time = 1000; break; // Full note + case '2': time = 500; break; // Half note + case '4': time = 250; break; // Quarter note + case '8': time = 50; break; // Eigth note + // Modifier '.' makes note length 2/3 + + } + } +} + +void RobotControl::beep(int beep_length){ + char scr1[]="8F"; + char scr2[]="8Fe"; + char scr3[]="1F"; + + switch (beep_length) + { + case BEEP_SIMPLE: + default: + playMelody(scr1); + break; + + case BEEP_DOUBLE: + playMelody(scr2); + break; + + case BEEP_LONG: + playMelody(scr3); + } + +} + +void RobotControl::tempoWrite(int tempo){ + SquawkSynthSD::tempo(tempo); +} +void RobotControl::tuneWrite(float tune){ + SquawkSynthSD::tune(tune); +} + +void RobotControl::playFile(char* filename){ + melody.open(filename,O_READ); + SquawkSynthSD::play(melody); +} + +void RobotControl::stopPlayFile(){ + melody.close(); +} \ No newline at end of file diff --git a/libraries/Robot_Control/Motors.cpp b/libraries/Robot_Control/Motors.cpp new file mode 100644 index 00000000000..12096fd5075 --- /dev/null +++ b/libraries/Robot_Control/Motors.cpp @@ -0,0 +1 @@ +#include "ArduinoRobot.h" #include "EasyTransfer2.h" void RobotControl::motorsStop(){ messageOut.writeByte(COMMAND_MOTORS_STOP); messageOut.sendData(); } void RobotControl::motorsWrite(int speedLeft,int speedRight){ messageOut.writeByte(COMMAND_RUN); messageOut.writeInt(speedLeft); messageOut.writeInt(speedRight); messageOut.sendData(); } void RobotControl::motorsWritePct(int speedLeftPct, int speedRightPct){ int16_t speedLeft=255*speedLeftPct/100.0; int16_t speedRight=255*speedRightPct/100.0; motorsWrite(speedLeft,speedRight); } void RobotControl::pointTo(int angle){ int target=angle; uint8_t speed=80; target=target%360; if(target<0){ target+=360; } int direction=angle; while(1){ int currentAngle=compassRead(); int diff=target-currentAngle; direction=180-(diff+360)%360; if(direction>0){ motorsWrite(speed,-speed);//right delay(10); }else{ motorsWrite(-speed,speed);//left delay(10); } //if(diff<-180) // diff += 360; //else if(diff> 180) // diff -= 360; //direction=-diff; if(abs(diff)<5){ motorsStop(); return; } } } void RobotControl::turn(int angle){ int originalAngle=compassRead(); int target=originalAngle+angle; pointTo(target); /*uint8_t speed=80; target=target%360; if(target<0){ target+=360; } int direction=angle; while(1){ if(direction>0){ motorsWrite(speed,speed);//right delay(10); }else{ motorsWrite(-speed,-speed);//left delay(10); } int currentAngle=compassRead(); int diff=target-currentAngle; if(diff<-180) diff += 360; else if(diff> 180) diff -= 360; direction=-diff; if(abs(diff)<5){ motorsWrite(0,0); return; } }*/ } void RobotControl::moveForward(int speed){ motorsWrite(speed,speed); } void RobotControl::moveBackward(int speed){ motorsWrite(speed,speed); } void RobotControl::turnLeft(int speed){ motorsWrite(speed,255); } void RobotControl::turnRight(int speed){ motorsWrite(255,speed); } /* int RobotControl::getIRrecvResult(){ messageOut.writeByte(COMMAND_GET_IRRECV); messageOut.sendData(); //delay(10); while(!messageIn.receiveData()); if(messageIn.readByte()==COMMAND_GET_IRRECV_RE){ return messageIn.readInt(); } return -1; } */ \ No newline at end of file diff --git a/libraries/Robot_Control/Multiplexer.cpp b/libraries/Robot_Control/Multiplexer.cpp new file mode 100644 index 00000000000..8f7d30e852f --- /dev/null +++ b/libraries/Robot_Control/Multiplexer.cpp @@ -0,0 +1,37 @@ +#include "Multiplexer.h" + +void Multiplexer::begin(uint8_t* selectors, uint8_t Z, uint8_t length){ + for(uint8_t i=0;iselectors[i]=selectors[i]; + pinMode(selectors[i],OUTPUT); + } + this->length=length; + this->pin_Z=Z; + pinMode(pin_Z,INPUT); +} + +void Multiplexer::selectPin(uint8_t num){ + for(uint8_t i=0;i= 100 +#include "Arduino.h" +#else +#include "WProgram.h" +#endif + +class Multiplexer{ + public: + void begin(uint8_t* selectors, uint8_t Z, uint8_t length); + void selectPin(uint8_t num); + int getAnalogValue(); + int getAnalogValueAt(uint8_t num); + bool getDigitalValue(); + bool getDigitalValueAt(uint8_t num); + private: + uint8_t selectors[4]; + uint8_t pin_Z; + uint8_t length; +}; + +#endif diff --git a/libraries/Robot_Control/RobotSdCard.cpp b/libraries/Robot_Control/RobotSdCard.cpp new file mode 100644 index 00000000000..df833d2c70f --- /dev/null +++ b/libraries/Robot_Control/RobotSdCard.cpp @@ -0,0 +1,22 @@ +#include + +void RobotControl::beginSD(){ + card.init(); + file.init(&card); + melody.init(&card); +} + +void RobotControl::_enableSD(){ + DDRB = DDRB & 0xDF; //pinMode(CS_LCD,INPUT); + DDRB = DDRB | 0x10; //pinMode(CS_SD,OUTPUT); +} + +/* +void RobotControl::sdTest(){ + file.open("Infor.txt",O_READ); + uint8_t buf[7]; + char n; + while ((n = file.read(buf, sizeof(buf))) > 0) { + for (uint8_t i = 0; i < n; i++) Serial.write(buf[i]); + } +}*/ \ No newline at end of file diff --git a/libraries/Robot_Control/SdCard.cpp b/libraries/Robot_Control/SdCard.cpp new file mode 100644 index 00000000000..fbbd8bc7ae9 --- /dev/null +++ b/libraries/Robot_Control/SdCard.cpp @@ -0,0 +1,279 @@ +/* Arduino FAT16 Library + * Copyright (C) 2008 by William Greiman + * + * This file is part of the Arduino FAT16 Library + * + * This Library is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This Library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with the Arduino Fat16 Library. If not, see + * . + */ +#include +#if ARDUINO < 100 +#include +#else // ARDUINO +#include +#endif // ARDUINO +#include +#include +//------------------------------------------------------------------------------ +// r1 status values +uint8_t const R1_READY_STATE = 0; +uint8_t const R1_IDLE_STATE = 1; +// start data token for read or write +uint8_t const DATA_START_BLOCK = 0XFE; +// data response tokens for write block +uint8_t const DATA_RES_MASK = 0X1F; +uint8_t const DATA_RES_ACCEPTED = 0X05; +uint8_t const DATA_RES_CRC_ERROR = 0X0B; +uint8_t const DATA_RES_WRITE_ERROR = 0X0D; +// +// stop compiler from inlining where speed optimization is not required +#define STATIC_NOINLINE static __attribute__((noinline)) +//------------------------------------------------------------------------------ +// SPI static functions +// +// clock byte in +STATIC_NOINLINE uint8_t spiRec(void) { + SPDR = 0xff; + while (!(SPSR & (1 << SPIF))); + return SPDR; +} +// clock byte out +STATIC_NOINLINE void spiSend(uint8_t b) { + SPDR = b; + while (!(SPSR & (1 << SPIF))); +} +//------------------------------------------------------------------------------ +// wait for card to go not busy +// return false if timeout +static uint8_t waitForToken(uint8_t token, uint16_t timeoutMillis) { + uint16_t t0 = millis(); + while (spiRec() != token) { + if (((uint16_t)millis() - t0) > timeoutMillis) return false; + } + return true; +} +//------------------------------------------------------------------------------ +uint8_t SdCard::cardCommand(uint8_t cmd, uint32_t arg) { + uint8_t r1; + + // select card + chipSelectLow(); + + // wait if busy + waitForToken(0XFF, SD_COMMAND_TIMEOUT); + + // send command + spiSend(cmd | 0x40); + + // send argument + for (int8_t s = 24; s >= 0; s -= 8) spiSend(arg >> s); + + // send CRC - must send valid CRC for CMD0 + spiSend(cmd == CMD0 ? 0x95 : 0XFF); + + // wait for not busy + for (uint8_t retry = 0; (0X80 & (r1 = spiRec())) && retry != 0XFF; retry++); + return r1; +} +//------------------------------------------------------------------------------ +uint8_t SdCard::cardAcmd(uint8_t cmd, uint32_t arg) { + cardCommand(CMD55, 0); + return cardCommand(cmd, arg); +} +//============================================================================== +// SdCard member functions +//------------------------------------------------------------------------------ +/** + * Determine the size of a standard SD flash memory card + * \return The number of 512 byte data blocks in the card + */ +uint32_t SdCard::cardSize(void) { + uint16_t c_size; + csd_t csd; + if (!readReg(CMD9, &csd)) return 0; + uint8_t read_bl_len = csd.read_bl_len; + c_size = (csd.c_size_high << 10) | (csd.c_size_mid << 2) | csd.c_size_low; + uint8_t c_size_mult = (csd.c_size_mult_high << 1) | csd.c_size_mult_low; + return (uint32_t)(c_size+1) << (c_size_mult + read_bl_len - 7); +} +//------------------------------------------------------------------------------ +void SdCard::chipSelectHigh(void) { + digitalWrite(chipSelectPin_, HIGH); + // make sure MISO goes high impedance + spiSend(0XFF); +} +//------------------------------------------------------------------------------ +void SdCard::chipSelectLow(void) { + // Enable SPI, Master, clock rate F_CPU/4 + SPCR = (1 << SPE) | (1 << MSTR); + + // Doubled Clock Frequency to F_CPU/2 unless speed_ is nonzero + if (!speed_) SPSR |= (1 << SPI2X); + + digitalWrite(chipSelectPin_, LOW); +} +//------------------------------------------------------------------------------ +void SdCard::error(uint8_t code, uint8_t data) { + errorData = data; + error(code); +} +//------------------------------------------------------------------------------ +void SdCard::error(uint8_t code) { + errorCode = code; + chipSelectHigh(); +} +//------------------------------------------------------------------------------ +/** + * Initialize a SD flash memory card. + * + * \param[in] speed Set SPI Frequency to F_CPU/2 if speed = 0 or F_CPU/4 + * if speed = 1. + * \param[in] chipSelectPin SD chip select pin number. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + * + */ +uint8_t SdCard::init(uint8_t speed, uint8_t chipSelectPin) { + if (speed > 1) { + error(SD_ERROR_SPI_SPEED); + return false; + } + speed_ = speed; + chipSelectPin_ = chipSelectPin; + errorCode = 0; + uint8_t r; + // 16-bit init start time allows over a minute + uint16_t t0 = (uint16_t)millis(); + + pinMode(chipSelectPin_, OUTPUT); + digitalWrite(chipSelectPin_, HIGH); + pinMode(SPI_MISO_PIN, INPUT); + pinMode(SPI_SS_PIN, OUTPUT); + pinMode(SPI_MOSI_PIN, OUTPUT); + pinMode(SPI_SCK_PIN, OUTPUT); + + // Enable SPI, Master, clock rate F_CPU/128 + SPCR = (1 << SPE) | (1 << MSTR) | (1 << SPR1) | (1 << SPR0); + + // must supply min of 74 clock cycles with CS high. + for (uint8_t i = 0; i < 10; i++) spiSend(0XFF); + digitalWrite(chipSelectPin_, LOW); + + // command to go idle in SPI mode + while ((r = cardCommand(CMD0, 0)) != R1_IDLE_STATE) { + if (((uint16_t)millis() - t0) > SD_INIT_TIMEOUT) { + error(SD_ERROR_CMD0, r); + return false; + } + } + // start initialization and wait for completed initialization + while ((r = cardAcmd(ACMD41, 0)) != R1_READY_STATE) { + if (((uint16_t)millis() - t0) > SD_INIT_TIMEOUT) { + error(SD_ERROR_ACMD41, r); + return false; + } + } + chipSelectHigh(); + return true; +} +//------------------------------------------------------------------------------ +/** + * Reads a 512 byte block from a storage device. + * + * \param[in] blockNumber Logical block to be read. + * \param[out] dst Pointer to the location that will receive the data. + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +uint8_t SdCard::readBlock(uint32_t blockNumber, uint8_t* dst) { + if (cardCommand(CMD17, blockNumber << 9)) { + error(SD_ERROR_CMD17); + return false; + } + return readTransfer(dst, 512); +} +//------------------------------------------------------------------------------ +uint8_t SdCard::readReg(uint8_t cmd, void* buf) { + uint8_t* dst = reinterpret_cast(buf); + if (cardCommand(cmd, 0)) { + chipSelectHigh(); + return false; + } + return readTransfer(dst, 16); +} +//------------------------------------------------------------------------------ +uint8_t SdCard::readTransfer(uint8_t* dst, uint16_t count) { + // wait for start of data + if (!waitForToken(DATA_START_BLOCK, SD_READ_TIMEOUT)) { + error(SD_ERROR_READ_TIMEOUT); + } + // start first spi transfer + SPDR = 0XFF; + for (uint16_t i = 0; i < count; i++) { + while (!(SPSR & (1 << SPIF))); + dst[i] = SPDR; + SPDR = 0XFF; + } + // wait for first CRC byte + while (!(SPSR & (1 << SPIF))); + spiRec(); // second CRC byte + chipSelectHigh(); + return true; +} +//------------------------------------------------------------------------------ +/** + * Writes a 512 byte block to a storage device. + * + * \param[in] blockNumber Logical block to be written. + * \param[in] src Pointer to the location of the data to be written. + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +uint8_t SdCard::writeBlock(uint32_t blockNumber, const uint8_t* src) { + uint32_t address = blockNumber << 9; +#if SD_PROTECT_BLOCK_ZERO + // don't allow write to first block + if (address == 0) { + error(SD_ERROR_BLOCK_ZERO_WRITE); + return false; + } +#endif // SD_PROTECT_BLOCK_ZERO + if (cardCommand(CMD24, address)) { + error(SD_ERROR_CMD24); + return false; + } + // optimize write loop + SPDR = DATA_START_BLOCK; + for (uint16_t i = 0; i < 512; i++) { + while (!(SPSR & (1 << SPIF))); + SPDR = src[i]; + } + while (!(SPSR & (1 << SPIF))); // wait for last data byte + spiSend(0xFF); // dummy crc + spiSend(0xFF); // dummy crc + + // get write response + uint8_t r1 = spiRec(); + if ((r1 & DATA_RES_MASK) != DATA_RES_ACCEPTED) { + error(SD_ERROR_WRITE_RESPONSE, r1); + return false; + } + // wait for card to complete write programming + if (!waitForToken(0XFF, SD_WRITE_TIMEOUT)) { + error(SD_ERROR_WRITE_TIMEOUT); + } + chipSelectHigh(); + return true; +} diff --git a/libraries/Robot_Control/SdCard.h b/libraries/Robot_Control/SdCard.h new file mode 100644 index 00000000000..c03e6ab1c74 --- /dev/null +++ b/libraries/Robot_Control/SdCard.h @@ -0,0 +1,192 @@ +/* Arduino FAT16 Library + * Copyright (C) 2008 by William Greiman + * + * This file is part of the Arduino FAT16 Library + * + * This Library is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This Library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with the Arduino Fat16 Library. If not, see + * . + */ +#ifndef SdCard_h +#define SdCard_h + /** + * \file + * SdCard class + */ +#include +//------------------------------------------------------------------------------ +// Warning only SD_CHIP_SELECT_PIN, the SD card select pin, may be redefined. +// define hardware SPI pins +#if defined(__AVR_ATmega168__)\ +||defined(__AVR_ATmega168P__)\ +||defined(__AVR_ATmega328P__) +// 168 and 328 Arduinos +/** Slave Select pin */ +uint8_t const SPI_SS_PIN = 10; +/** Master Out Slave In pin */ +uint8_t const SPI_MOSI_PIN = 11; +/** Master In Slave Out pin */ +uint8_t const SPI_MISO_PIN = 12; +/** Serial Clock */ +uint8_t const SPI_SCK_PIN = 13; +//------------------------------------------------------------------------------ +#elif defined(__AVR_ATmega1280__)\ +|| defined(__AVR_ATmega2560__) +// pins for Arduino Mega +uint8_t const SPI_SS_PIN = 53; +uint8_t const SPI_MOSI_PIN = 51; +uint8_t const SPI_MISO_PIN = 50; +uint8_t const SPI_SCK_PIN = 52; +//------------------------------------------------------------------------------ +#elif defined(__AVR_ATmega644P__)\ +|| defined(__AVR_ATmega644__)\ +|| defined(__AVR_ATmega1284P__) +// pins for Sanguino +uint8_t const SPI_SS_PIN = 4; +uint8_t const SPI_MOSI_PIN = 5; +uint8_t const SPI_MISO_PIN = 6; +uint8_t const SPI_SCK_PIN = 7; +//------------------------------------------------------------------------------ +#elif defined(__AVR_ATmega32U4__) +// pins for Teensy 2.0 +uint8_t const SPI_SS_PIN = 8; +uint8_t const SPI_MOSI_PIN = 16; +uint8_t const SPI_MISO_PIN = 14; +uint8_t const SPI_SCK_PIN = 15; +//------------------------------------------------------------------------------ +#elif defined(__AVR_AT90USB646__)\ +|| defined(__AVR_AT90USB1286__) +// pins for Teensy++ 1.0 & 2.0 +uint8_t const SPI_SS_PIN = 20; +uint8_t const SPI_MOSI_PIN = 22; +uint8_t const SPI_MISO_PIN = 23; +uint8_t const SPI_SCK_PIN = 21; +//------------------------------------------------------------------------------ +#else // SPI pins +#error unknown CPU +#endif // SPI pins +//------------------------------------------------------------------------------ +/** + * SD Chip Select pin + * + * Warning if this pin is redefined the hardware SS pin will be enabled + * as an output by init(). An avr processor will not function as an SPI + * master unless SS is set to output mode. + * + * For example to set SD_CHIP_SELECT_PIN to 8 for the SparkFun microSD shield: + * uint8_t const SD_CHIP_SELECT_PIN = 8; + * + * The default chip select pin for the SD card is SS. + */ +uint8_t const SD_CHIP_SELECT_PIN = SPI_SS_PIN; +//------------------------------------------------------------------------------ +/** command timeout ms */ +uint16_t const SD_COMMAND_TIMEOUT = 300; +/** init timeout ms */ +uint16_t const SD_INIT_TIMEOUT = 2000; +/** read timeout ms */ +uint16_t const SD_READ_TIMEOUT = 300; +/** write timeout ms */ +uint16_t const SD_WRITE_TIMEOUT = 600; +//------------------------------------------------------------------------------ +// error codes +/** Card did not go into SPI mode */ +uint8_t const SD_ERROR_CMD0 = 1; +/** Card did not go ready */ +uint8_t const SD_ERROR_ACMD41 = 2; +/** Write command not accepted */ +uint8_t const SD_ERROR_CMD24 = 3; +/** Read command not accepted */ +uint8_t const SD_ERROR_CMD17 = 4; +/** timeout waiting for read data */ +uint8_t const SD_ERROR_READ_TIMEOUT = 5; +/** write error occurred */ +uint8_t const SD_ERROR_WRITE_RESPONSE = 6; +/** timeout waiting for write status */ +uint8_t const SD_ERROR_WRITE_TIMEOUT = 7; +/** attempt to write block zero */ +uint8_t const SD_ERROR_BLOCK_ZERO_WRITE = 8; +/** card returned an error to a CMD13 status check after a write */ +uint8_t const SD_ERROR_WRITE_PROGRAMMING = 9; +/** invalid SPI speed in init() call */ +uint8_t const SD_ERROR_SPI_SPEED = 10; +//------------------------------------------------------------------------------ +// SD command codes +/** SEND OPERATING CONDITIONS */ +uint8_t const ACMD41 = 0X29; +/** GO_IDLE_STATE - init card in spi mode if CS low */ +uint8_t const CMD0 = 0X00; +/** SEND_CSD - Card Specific Data */ +uint8_t const CMD9 = 0X09; +/** SEND_CID - Card IDentification */ +uint8_t const CMD10 = 0X0A; +/** SEND_STATUS - read the card status register */ +uint8_t const CMD13 = 0X0D; +/** READ_BLOCK */ +uint8_t const CMD17 = 0X11; +/** WRITE_BLOCK */ +uint8_t const CMD24 = 0X18; +/** APP_CMD - escape for application specific command */ +uint8_t const CMD55 = 0X37; +//------------------------------------------------------------------------------ +/** + * \class SdCard + * \brief Hardware access class for SD flash cards + * + * Supports raw access to a standard SD flash memory card. + * + */ +class SdCard { + public: + /** Code for a SD error. See SdCard.h for definitions. */ + uint8_t errorCode; + /** Data that may be helpful in determining the cause of an error */ + uint8_t errorData; + uint32_t cardSize(void); + /** + * Initialize an SD flash memory card with default clock rate and chip + * select pin. See SdCard::init(uint8_t sckRateID, uint8_t chipSelectPin). + */ + uint8_t init(void) { + return init(0, SD_CHIP_SELECT_PIN); + } + /** + * Initialize an SD flash memory card with the selected SPI clock rate + * and the default SD chip select pin. + * See SdCard::init(uint8_t slow, uint8_t chipSelectPin). + */ + uint8_t init(uint8_t speed) { + return init(speed, SD_CHIP_SELECT_PIN); + } + uint8_t init(uint8_t speed, uint8_t chipselectPin); + uint8_t readBlock(uint32_t block, uint8_t* dst); + /** Read the CID register which contains info about the card. + * This includes Manufacturer ID, OEM ID, product name, version, + * serial number, and manufacturing date. */ + uint8_t readCID(cid_t* cid) { + return readReg(CMD10, cid); + } + uint8_t writeBlock(uint32_t block, const uint8_t* src); + private: + uint8_t cardAcmd(uint8_t cmd, uint32_t arg); + uint8_t cardCommand(uint8_t cmd, uint32_t arg); + uint8_t chipSelectPin_; + uint8_t speed_; + void chipSelectHigh(void); + void chipSelectLow(void); + void error(uint8_t code, uint8_t data); + void error(uint8_t code); + uint8_t readReg(uint8_t cmd, void* buf); + uint8_t readTransfer(uint8_t* dst, uint16_t count); +}; +#endif // SdCard_h diff --git a/libraries/Robot_Control/SdInfo.h b/libraries/Robot_Control/SdInfo.h new file mode 100644 index 00000000000..4c82e0b1edb --- /dev/null +++ b/libraries/Robot_Control/SdInfo.h @@ -0,0 +1,117 @@ +/* Arduino FAT16 Library + * Copyright (C) 2008 by William Greiman + * + * This file is part of the Arduino FAT16 Library + * + * This Library is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This Library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with the Arduino Fat16 Library. If not, see + * . + */ +#ifndef SdInfo_h +#define SdInfo_h +#include +// Based on the document: +// +// SD Specifications +// Part 1 +// Physical Layer +// Simplified Specification +// Version 2.00 +// September 25, 2006 +// +// www.sdcard.org/developers/tech/sdcard/pls/Simplified_Physical_Layer_Spec.pdf +// +// Card IDentification (CID) register +typedef struct CID { + // byte 0 + uint8_t mid; // Manufacturer ID + // byte 1-2 + char oid[2]; // OEM/Application ID + // byte 3-7 + char pnm[5]; // Product name + // byte 8 + unsigned prv_m : 4; // Product revision n.m + unsigned prv_n : 4; + // byte 9-12 + uint32_t psn; // Product serial number + // byte 13 + unsigned mdt_year_high : 4; // Manufacturing date + unsigned reserved : 4; + // byte 14 + unsigned mdt_month : 4; + unsigned mdt_year_low :4; + // byte 15 + unsigned always1 : 1; + unsigned crc : 7; +}cid_t; +// Card-Specific Data register +typedef struct CSD { + // byte 0 + unsigned reserved1 : 6; + unsigned csd_ver : 2; + // byte 1 + uint8_t taac; + // byte 2 + uint8_t nsac; + // byte 3 + uint8_t tran_speed; + // byte 4 + uint8_t ccc_high; + // byte 5 + unsigned read_bl_len : 4; + unsigned ccc_low : 4; + // byte 6 + unsigned c_size_high : 2; + unsigned reserved2 : 2; + unsigned dsr_imp : 1; + unsigned read_blk_misalign :1; + unsigned write_blk_misalign : 1; + unsigned read_bl_partial : 1; + // byte 7 + uint8_t c_size_mid; + // byte 8 + unsigned vdd_r_curr_max : 3; + unsigned vdd_r_curr_min : 3; + unsigned c_size_low :2; + // byte 9 + unsigned c_size_mult_high : 2; + unsigned vdd_w_cur_max : 3; + unsigned vdd_w_curr_min : 3; + // byte 10 + unsigned sector_size_high : 6; + unsigned erase_blk_en : 1; + unsigned c_size_mult_low : 1; + // byte 11 + unsigned wp_grp_size : 7; + unsigned sector_size_low : 1; + // byte 12 + unsigned write_bl_len_high : 2; + unsigned r2w_factor : 3; + unsigned reserved3 : 2; + unsigned wp_grp_enable : 1; + // byte 13 + unsigned reserved4 : 5; + unsigned write_partial : 1; + unsigned write_bl_len_low : 2; + // byte 14 + unsigned reserved5: 2; + unsigned file_format : 2; + unsigned tmp_write_protect : 1; + unsigned perm_write_protect : 1; + unsigned copy : 1; + unsigned file_format_grp : 1; + // byte 15 + unsigned always1 : 1; + unsigned crc : 7; +}csd_t; +#endif // SdInfo_h diff --git a/libraries/Robot_Control/Sensors.cpp b/libraries/Robot_Control/Sensors.cpp new file mode 100644 index 00000000000..b651c28a4c5 --- /dev/null +++ b/libraries/Robot_Control/Sensors.cpp @@ -0,0 +1,274 @@ +#include "ArduinoRobot.h" +#include "Multiplexer.h" +#include "Wire.h" +bool RobotControl::digitalRead(uint8_t port){ + uint8_t type=_getTypeCode(port); + switch(type){ + case TYPE_TOP_TK: + return _digitalReadTopMux(port); + break; + case TYPE_TOP_TKD: + return _digitalReadTopPin(port); + break; + case TYPE_BOTTOM_TK: + return _requestDigitalRead(port); + break; + } +} +int RobotControl::analogRead(uint8_t port){ + uint8_t type=_getTypeCode(port); + switch(type){ + case TYPE_TOP_TK: + return _analogReadTopMux(port); + break; + case TYPE_TOP_TKD: + return _analogReadTopPin(port); + break; + case TYPE_BOTTOM_TK: + return _requestAnalogRead(port); + break; + } +} +void RobotControl::digitalWrite(uint8_t port, bool value){ + uint8_t type=_getTypeCode(port); + switch(type){ + case TYPE_TOP_TK: + //Top TKs can't use digitalWrite? + break; + case TYPE_TOP_TKD: + _digitalWriteTopPin(port, value); + break; + case TYPE_BOTTOM_TK: + _requestDigitalWrite(port, value); + break; + } +} +void RobotControl::analogWrite(uint8_t port, uint8_t value){ + if(port==TKD4) + ::analogWrite(port,value); +} + +uint8_t RobotControl::_getTypeCode(uint8_t port){ + switch(port){ + case TK0: + case TK1: + case TK2: + case TK3: + case TK4: + case TK5: + case TK6: + case TK7: + return TYPE_TOP_TK; + break; + + case TKD0: + case TKD1: + case TKD2: + case TKD3: + case TKD4: + case TKD5: + case LED1: + return TYPE_TOP_TKD; + break; + + case B_TK1: + case B_TK2: + case B_TK3: + case B_TK4: + return TYPE_BOTTOM_TK; + break; + } +} +uint8_t RobotControl::_portToTopMux(uint8_t port){ + switch(port){ + case TK0: + return 0; + case TK1: + return 1; + case TK2: + return 2; + case TK3: + return 3; + case TK4: + return 4; + case TK5: + return 5; + case TK6: + return 6; + case TK7: + return 7; + } +} +uint8_t RobotControl::_topDPortToAPort(uint8_t port){ + switch(port){ + case TKD0: + return A1; + case TKD1: + return A2; + case TKD2: + return A3; + case TKD3: + return A4; + case TKD4: + return A7; + case TKD5: + return A11; + } +} +int* RobotControl::parseMBDPort(uint8_t port){ + //Serial.println(port); + switch(port){ + case B_TK1: + return &motorBoardData._B_TK1; + case B_TK2: + return &motorBoardData._B_TK2; + case B_TK3: + return &motorBoardData._B_TK3; + case B_TK4: + return &motorBoardData._B_TK4; + + /* + case B_IR0: + return &motorBoardData._B_IR0; + case B_IR1: + return &motorBoardData._B_IR1; + case B_IR2: + return &motorBoardData._B_IR2; + case B_IR3: + return &motorBoardData._B_IR3; + case B_IR4: + return &motorBoardData._B_IR4;*/ + } +} +int RobotControl::get_motorBoardData(uint8_t port){ + return *parseMBDPort(port); +} +void RobotControl::set_motorBoardData(uint8_t port, int data){ + *parseMBDPort(port)=data; +} + +bool RobotControl::_digitalReadTopMux(uint8_t port){ + uint8_t num=_portToTopMux(port); + return Multiplexer::getDigitalValueAt(num); +} + +int RobotControl::_analogReadTopMux(uint8_t port){ + uint8_t num=_portToTopMux(port); + return Multiplexer::getAnalogValueAt(num); +} + +bool RobotControl::_digitalReadTopPin(uint8_t port){ + return ::digitalRead(port); +} +int RobotControl::_analogReadTopPin(uint8_t port){ + uint8_t aPin=_topDPortToAPort(port); + return ::analogRead(aPin); +} +void RobotControl::_digitalWriteTopPin(uint8_t port, bool value){ + ::digitalWrite(port, value); +} + +bool RobotControl::_requestDigitalRead(uint8_t port){ + messageOut.writeByte(COMMAND_DIGITAL_READ); + messageOut.writeByte(port);//B_TK1 - B_TK4 + messageOut.sendData(); + delay(10); + if(messageIn.receiveData()){ + //Serial.println("*************"); + uint8_t cmd=messageIn.readByte(); + //Serial.print("cmd: "); + //Serial.println(cmd); + if(!(cmd==COMMAND_DIGITAL_READ_RE)) + return false; + + uint8_t pt=messageIn.readByte(); //Bottom TK port codename + //Serial.print("pt: "); + //Serial.println(pt); + set_motorBoardData(pt,messageIn.readByte()); + return get_motorBoardData(port); + } +} +int RobotControl::_requestAnalogRead(uint8_t port){ + messageOut.writeByte(COMMAND_ANALOG_READ); + messageOut.writeByte(port);//B_TK1 - B_TK4 + messageOut.sendData(); + delay(10); + if(messageIn.receiveData()){ + uint8_t cmd=messageIn.readByte(); + //Serial.println("*************"); + //Serial.print("cmd: "); + //Serial.println(cmd); + if(!(cmd==COMMAND_ANALOG_READ_RE)) + return false; + + uint8_t pt=messageIn.readByte(); + //Serial.print("pt: "); + //Serial.println(pt); + set_motorBoardData(pt,messageIn.readInt()); + return get_motorBoardData(port); + } +} +void RobotControl::_requestDigitalWrite(uint8_t selector, uint8_t value){ + messageOut.writeByte(COMMAND_DIGITAL_WRITE); + messageOut.writeByte(selector);//B_TK1 - B_TK4 + messageOut.writeByte(value); + messageOut.sendData(); +} + + + + + +void RobotControl::updateIR(){ + messageOut.writeByte(COMMAND_READ_IR); + messageOut.sendData(); + delay(10); + if(messageIn.receiveData()){ + if(messageIn.readByte()==COMMAND_READ_IR_RE){ + for(int i=0;i<5;i++){ + IRarray[i]=messageIn.readInt(); + } + } + } +} + +int RobotControl::knobRead(){ + return ::analogRead(POT); +} + +int RobotControl::trimRead(){ + messageOut.writeByte(COMMAND_READ_TRIM); + messageOut.sendData(); + delay(10); + if(messageIn.receiveData()){ + uint8_t cmd=messageIn.readByte(); + if(!(cmd==COMMAND_READ_TRIM_RE)) + return false; + + uint16_t pt=messageIn.readInt(); + return pt; + } +} + +uint16_t RobotControl::compassRead(){ + return Compass::getReading(); +} + +/* +void RobotControl::beginUR(uint8_t pinTrigger, uint8_t pinEcho){ + pinTrigger_UR=pinTrigger; + pinEcho_UR=pinEcho; + + pinMode(pinEcho_UR, INPUT); + pinMode(pinTrigger_UR, OUTPUT); +} +uint16_t RobotControl::getDistance(){ + digitalWrite(pinTrigger_UR, LOW); // Set the trigger pin to low for 2uS + delayMicroseconds(2); + digitalWrite(pinTrigger_UR, HIGH); // Send a 10uS high to trigger ranging + delayMicroseconds(10); + digitalWrite(pinTrigger_UR, LOW); // Send pin low again + uint16_t distance = pulseIn(pinEcho_UR, HIGH); // Read in times pulse + distance= distance/58; // Calculate distance from time of pulse + return distance; +}*/ \ No newline at end of file diff --git a/libraries/Robot_Control/Squawk.cpp b/libraries/Robot_Control/Squawk.cpp new file mode 100644 index 00000000000..5b39ebea1ac --- /dev/null +++ b/libraries/Robot_Control/Squawk.cpp @@ -0,0 +1,601 @@ +// Squawk Soft-Synthesizer Library for Arduino +// +// Davey Taylor 2013 +// d.taylor@arduino.cc + +#include "Squawk.h" + +// Period range, used for clamping +#define PERIOD_MIN 28 +#define PERIOD_MAX 3424 + +// Convenience macros +#define LO4(V) ((V) & 0x0F) +#define HI4(V) (((V) & 0xF0) >> 4) +#define MIN(A, B) ((A) < (B) ? (A) : (B)) +#define MAX(A, B) ((A) > (B) ? (A) : (B)) +#define FREQ(PERIOD) (tuning_long / (PERIOD)) + +// SquawkStream class for PROGMEM data +class StreamROM : public SquawkStream { + private: + uint8_t *p_start; + uint8_t *p_cursor; + public: + StreamROM(const uint8_t *p_rom = NULL) { p_start = p_cursor = (uint8_t*)p_rom; } + uint8_t read() { return pgm_read_byte(p_cursor++); } + void seek(size_t offset) { p_cursor = p_start + offset; } +}; + +// Oscillator memory +typedef struct { + uint8_t fxp; + uint8_t offset; + uint8_t mode; +} pto_t; + +// Deconstructed cell +typedef struct { + uint8_t fxc, fxp, ixp; +} cel_t; + +// Effect memory +typedef struct { + int8_t volume; + uint8_t port_speed; + uint16_t port_target; + bool glissando; + pto_t vibr; + pto_t trem; + uint16_t period; + uint8_t param; +} fxm_t; + +// Locals +static uint8_t order_count; +static uint8_t order[64]; +static uint8_t speed; +static uint8_t tick; +static uint8_t ix_row; +static uint8_t ix_order; +static uint8_t ix_nextrow; +static uint8_t ix_nextorder; +static uint8_t row_delay; +static fxm_t fxm[4]; +static cel_t cel[4]; +static uint32_t tuning_long; +static uint16_t sample_rate; +static float tuning = 1.0; +static uint16_t tick_rate = 50; + +static SquawkStream *stream; +static uint16_t stream_base; +static StreamROM rom; + +// Imports +extern intptr_t squawk_register; +extern uint16_t cia; + +// Exports +osc_t osc[4]; +uint8_t pcm = 128; + +// ProTracker period tables +uint16_t period_tbl[84] PROGMEM = { + 3424, 3232, 3048, 2880, 2712, 2560, 2416, 2280, 2152, 2032, 1920, 1814, + 1712, 1616, 1524, 1440, 1356, 1280, 1208, 1140, 1076, 1016, 960, 907, + 856, 808, 762, 720, 678, 640, 604, 570, 538, 508, 480, 453, + 428, 404, 381, 360, 339, 320, 302, 285, 269, 254, 240, 226, + 214, 202, 190, 180, 170, 160, 151, 143, 135, 127, 120, 113, + 107, 101, 95, 90, 85, 80, 75, 71, 67, 63, 60, 56, + 53, 50, 47, 45, 42, 40, 37, 35, 33, 31, 30, 28, +}; + +// ProTracker sine table +int8_t sine_tbl[32] PROGMEM = { + 0x00, 0x0C, 0x18, 0x25, 0x30, 0x3C, 0x47, 0x51, 0x5A, 0x62, 0x6A, 0x70, 0x76, 0x7A, 0x7D, 0x7F, + 0x7F, 0x7F, 0x7D, 0x7A, 0x76, 0x70, 0x6A, 0x62, 0x5A, 0x51, 0x47, 0x3C, 0x30, 0x25, 0x18, 0x0C, +}; + +// Squawk object +SquawkSynth Squawk; + +// Look up or generate waveform for ProTracker vibrato/tremolo oscillator +static int8_t do_osc(pto_t *p_osc) { + int8_t sample = 0; + int16_t mul; + switch(p_osc->mode & 0x03) { + case 0: // Sine + sample = pgm_read_byte(&sine_tbl[(p_osc->offset) & 0x1F]); + if(p_osc->offset & 0x20) sample = -sample; + break; + case 1: // Square + sample = (p_osc->offset & 0x20) ? 127 : -128; + break; + case 2: // Saw + sample = -(p_osc->offset << 2); + break; + case 3: // Noise (random) + sample = rand(); + break; + } + mul = sample * LO4(p_osc->fxp); + p_osc->offset = (p_osc->offset + HI4(p_osc->fxp)); + return mul >> 6; +} + +// Calculates and returns arpeggio period +// Essentially finds period of current note + halftones +static inline uint16_t arpeggio(uint8_t ch, uint8_t halftones) { + uint8_t n; + for(n = 0; n != 47; n++) { + if(fxm[ch].period >= pgm_read_word(&period_tbl[n])) break; + } + return pgm_read_word(&period_tbl[MIN(n + halftones, 47)]); +} + +// Calculates and returns glissando period +// Essentially snaps a sliding frequency to the closest note +static inline uint16_t glissando(uint8_t ch) { + uint8_t n; + uint16_t period_h, period_l; + for(n = 0; n != 47; n++) { + period_l = pgm_read_word(&period_tbl[n]); + period_h = pgm_read_word(&period_tbl[n + 1]); + if(fxm[ch].period < period_l && fxm[ch].period >= period_h) { + if(period_l - fxm[ch].period <= fxm[ch].period - period_h) { + period_h = period_l; + } + break; + } + } + return period_h; +} + +// Tunes Squawk to a different frequency +void SquawkSynth::tune(float new_tuning) { + tuning = new_tuning; + tuning_long = (long)(((double)3669213184.0 / (double)sample_rate) * (double)tuning); + +} + +// Sets tempo +void SquawkSynth::tempo(uint16_t new_tempo) { + tick_rate = new_tempo; + cia = sample_rate / tick_rate; // not atomic? +} + +// Initializes Squawk +// Sets up the selected port, and the sample grinding ISR +void SquawkSynth::begin(uint16_t hz) { + word isr_rr; + + sample_rate = hz; + tuning_long = (long)(((double)3669213184.0 / (double)sample_rate) * (double)tuning); + cia = sample_rate / tick_rate; + + if(squawk_register == (intptr_t)&OCR0A) { + // Squawk uses PWM on OCR0A/PD5(ATMega328/168)/PB7(ATMega32U4) +#ifdef __AVR_ATmega32U4__ + DDRB |= 0b10000000; // TODO: FAIL on 32U4 +#else + DDRD |= 0b01000000; +#endif + TCCR0A = 0b10000011; // Fast-PWM 8-bit + TCCR0B = 0b00000001; // 62500Hz + OCR0A = 0x7F; + } else if(squawk_register == (intptr_t)&OCR0B) { + // Squawk uses PWM on OCR0B/PC5(ATMega328/168)/PD0(ATMega32U4) +#ifdef __AVR_ATmega32U4__ + DDRD |= 0b00000001; +#else + DDRD |= 0b00100000; +#endif // Set timer mode to + TCCR0A = 0b00100011; // Fast-PWM 8-bit + TCCR0B = 0b00000001; // 62500Hz + OCR0B = 0x7F; +#ifdef OCR2A + } else if(squawk_register == (intptr_t)&OCR2A) { + // Squawk uses PWM on OCR2A/PB3 + DDRB |= 0b00001000; // Set timer mode to + TCCR2A = 0b10000011; // Fast-PWM 8-bit + TCCR2B = 0b00000001; // 62500Hz + OCR2A = 0x7F; +#endif +#ifdef OCR2B + } else if(squawk_register == (intptr_t)&OCR2B) { + // Squawk uses PWM on OCR2B/PD3 + DDRD |= 0b00001000; // Set timer mode to + TCCR2A = 0b00100011; // Fast-PWM 8-bit + TCCR2B = 0b00000001; // 62500Hz + OCR2B = 0x7F; +#endif +#ifdef OCR3AL + } else if(squawk_register == (intptr_t)&OCR3AL) { + // Squawk uses PWM on OCR3AL/PC6 + DDRC |= 0b01000000; // Set timer mode to + TCCR3A = 0b10000001; // Fast-PWM 8-bit + TCCR3B = 0b00001001; // 62500Hz + OCR3AH = 0x00; + OCR3AL = 0x7F; +#endif + } else if(squawk_register == (intptr_t)&SPDR) { + // NOT YET SUPPORTED + // Squawk uses external DAC via SPI + // TODO: Configure SPI + // TODO: Needs SS toggle in sample grinder + } else if(squawk_register == (intptr_t)&PORTB) { + // NOT YET SUPPORTED + // Squawk uses resistor ladder on PORTB + // TODO: Needs shift right in sample grinder + DDRB = 0b11111111; + } else if(squawk_register == (intptr_t)&PORTC) { + // NOT YET SUPPORTED + // Squawk uses resistor ladder on PORTC + // TODO: Needs shift right in sample grinder + DDRC = 0b11111111; + } + + // Seed LFSR (needed for noise) + osc[3].freq = 0x2000; + + // Set up ISR to run at sample_rate (may not be exact) + isr_rr = F_CPU / sample_rate; + TCCR1A = 0b00000000; // Set timer mode + TCCR1B = 0b00001001; + OCR1AH = isr_rr >> 8; // Set freq + OCR1AL = isr_rr & 0xFF; +} + +// Decrunches a 9 byte row into a useful data +static void decrunch_row() { + uint8_t data; + + // Initial decrunch + stream->seek(stream_base + ((order[ix_order] << 6) + ix_row) * 9); + data = stream->read(); cel[0].fxc = data << 0x04; + cel[1].fxc = data & 0xF0; + data = stream->read(); cel[0].fxp = data; + data = stream->read(); cel[1].fxp = data; + data = stream->read(); cel[2].fxc = data << 0x04; + cel[3].fxc = data >> 0x04; + data = stream->read(); cel[2].fxp = data; + data = stream->read(); cel[3].fxp = data; + data = stream->read(); cel[0].ixp = data; + data = stream->read(); cel[1].ixp = data; + data = stream->read(); cel[2].ixp = data; + + // Decrunch extended effects + if(cel[0].fxc == 0xE0) { cel[0].fxc |= cel[0].fxp >> 4; cel[0].fxp &= 0x0F; } + if(cel[1].fxc == 0xE0) { cel[1].fxc |= cel[1].fxp >> 4; cel[1].fxp &= 0x0F; } + if(cel[2].fxc == 0xE0) { cel[2].fxc |= cel[2].fxp >> 4; cel[2].fxp &= 0x0F; } + + // Decrunch cell 3 ghetto-style + cel[3].ixp = ((cel[3].fxp & 0x80) ? 0x00 : 0x7F) | ((cel[3].fxp & 0x40) ? 0x80 : 0x00); + cel[3].fxp &= 0x3F; + switch(cel[3].fxc) { + case 0x02: + case 0x03: if(cel[3].fxc & 0x01) cel[3].fxp |= 0x40; cel[3].fxp = (cel[3].fxp >> 4) | (cel[3].fxp << 4); cel[3].fxc = 0x70; break; + case 0x01: if(cel[3].fxp & 0x08) cel[3].fxp = (cel[3].fxp & 0x07) << 4; cel[3].fxc = 0xA0; break; + case 0x04: cel[3].fxc = 0xC0; break; + case 0x05: cel[3].fxc = 0xB0; break; + case 0x06: cel[3].fxc = 0xD0; break; + case 0x07: cel[3].fxc = 0xF0; break; + case 0x08: cel[3].fxc = 0xE7; break; + case 0x09: cel[3].fxc = 0xE9; break; + case 0x0A: cel[3].fxc = (cel[3].fxp & 0x08) ? 0xEA : 0xEB; cel[3].fxp &= 0x07; break; + case 0x0B: cel[3].fxc = (cel[3].fxp & 0x10) ? 0xED : 0xEC; cel[3].fxp &= 0x0F; break; + case 0x0C: cel[3].fxc = 0xEE; break; + } + + // Apply generic effect parameter memory + uint8_t ch; + cel_t *p_cel = cel; + fxm_t *p_fxm = fxm; + for(ch = 0; ch != 4; ch++) { + uint8_t fx = p_cel->fxc; + if(fx == 0x10 || fx == 0x20 || fx == 0xE1 || fx == 0xE2 || fx == 0x50 || fx == 0x60 || fx == 0xA0) { + if(p_cel->fxp) { + p_fxm->param = p_cel->fxp; + } else { + p_cel->fxp = p_fxm->param; + } + } + p_cel++; p_fxm++; + } +} + +// Resets playback +static void playroutine_reset() { + memset(fxm, 0, sizeof(fxm)); + tick = 0; + ix_row = 0; + ix_order = 0; + ix_nextrow = 0xFF; + ix_nextorder = 0xFF; + row_delay = 0; + speed = 6; + decrunch_row(); +} + +// Start grinding samples +void SquawkSynth::play() { + TIMSK1 = 1 << OCIE1A; // Enable interrupt +} + +// Load a melody stream and start grinding samples +void SquawkSynth::play(SquawkStream *melody) { + uint8_t n; + pause(); + stream = melody; + stream->seek(0); + n = stream->read(); + if(n == 'S') { + // Squawk SD file + stream->seek(4); + stream_base = stream->read() << 8; + stream_base |= stream->read(); + stream_base += 6; + } else { + // Squawk ROM array + stream_base = 1; + } + stream->seek(stream_base); + order_count = stream->read(); + if(order_count <= 64) { + stream_base += order_count + 1; + for(n = 0; n < order_count; n++) order[n] = stream->read(); + playroutine_reset(); + play(); + } else { + order_count = 0; + } +} + +// Load a melody in PROGMEM and start grinding samples +void SquawkSynth::play(const uint8_t *melody) { + pause(); + rom = StreamROM(melody); + play(&rom); +} + +// Pause playback +void SquawkSynth::pause() { + TIMSK1 = 0; // Disable interrupt +} + +// Stop playing, unload melody +void SquawkSynth::stop() { + pause(); + order_count = 0; // Unload melody +} + +// Progress module by one tick +void squawk_playroutine() { + static bool lockout = false; + + if(!order_count) return; + + // Protect from re-entry via ISR + cli(); + if(lockout) { + sei(); + return; + } + lockout = true; + sei(); + + // Handle row delay + if(row_delay) { + if(tick == 0) row_delay--; + // Advance tick + if(++tick == speed) tick = 0; + } else { + + // Quick pointer access + fxm_t *p_fxm = fxm; + osc_t *p_osc = osc; + cel_t *p_cel = cel; + + // Temps + uint8_t ch, fx, fxp; + bool pattern_jump = false; + uint8_t ix_period; + + for(ch = 0; ch != 4; ch++) { + uint8_t temp; + + // Local register copy + fx = p_cel->fxc; + fxp = p_cel->fxp; + ix_period = p_cel->ixp; + + // If first tick + if(tick == (fx == 0xED ? fxp : 0)) { + + // Reset volume + if(ix_period & 0x80) p_osc->vol = p_fxm->volume = 0x20; + + if((ix_period & 0x7F) != 0x7F) { + + // Reset oscillators (unless continous flag set) + if((p_fxm->vibr.mode & 0x4) == 0x0) p_fxm->vibr.offset = 0; + if((p_fxm->trem.mode & 0x4) == 0x0) p_fxm->trem.offset = 0; + + // Cell has note + if(fx == 0x30 || fx == 0x50) { + + // Tone-portamento effect setup + p_fxm->port_target = pgm_read_word(&period_tbl[ix_period & 0x7F]); + } else { + + // Set required effect memory parameters + p_fxm->period = pgm_read_word(&period_tbl[ix_period & 0x7F]); + + // Start note + if(ch != 3) p_osc->freq = FREQ(p_fxm->period); + + } + } + + // Effects processed when tick = 0 + switch(fx) { + case 0x30: // Portamento + if(fxp) p_fxm->port_speed = fxp; + break; + case 0xB0: // Jump to pattern + ix_nextorder = (fxp >= order_count ? 0x00 : fxp); + ix_nextrow = 0; + pattern_jump = true; + break; + case 0xC0: // Set volume + p_osc->vol = p_fxm->volume = MIN(fxp, 0x20); + break; + case 0xD0: // Jump to row + if(!pattern_jump) ix_nextorder = ((ix_order + 1) >= order_count ? 0x00 : ix_order + 1); + pattern_jump = true; + ix_nextrow = (fxp > 63 ? 0 : fxp); + break; + case 0xF0: // Set speed, BPM(CIA) not supported + if(fxp <= 0x20) speed = fxp; + break; + case 0x40: // Vibrato + if(fxp) p_fxm->vibr.fxp = fxp; + break; + case 0x70: // Tremolo + if(fxp) p_fxm->trem.fxp = fxp; + break; + case 0xE1: // Fine slide up + if(ch != 3) { + p_fxm->period = MAX(p_fxm->period - fxp, PERIOD_MIN); + p_osc->freq = FREQ(p_fxm->period); + } + break; + case 0xE2: // Fine slide down + if(ch != 3) { + p_fxm->period = MIN(p_fxm->period + fxp, PERIOD_MAX); + p_osc->freq = FREQ(p_fxm->period); + } + break; + case 0xE3: // Glissando control + p_fxm->glissando = (fxp != 0); + break; + case 0xE4: // Set vibrato waveform + p_fxm->vibr.mode = fxp; + break; + case 0xE7: // Set tremolo waveform + p_fxm->trem.mode = fxp; + break; + case 0xEA: // Fine volume slide up + p_osc->vol = p_fxm->volume = MIN(p_fxm->volume + fxp, 0x20); + break; + case 0xEB: // Fine volume slide down + p_osc->vol = p_fxm->volume = MAX(p_fxm->volume - fxp, 0); + break; + case 0xEE: // Delay + row_delay = fxp; + break; + } + } else { + + // Effects processed when tick > 0 + switch(fx) { + case 0x10: // Slide up + if(ch != 3) { + p_fxm->period = MAX(p_fxm->period - fxp, PERIOD_MIN); + p_osc->freq = FREQ(p_fxm->period); + } + break; + case 0x20: // Slide down + if(ch != 3) { + p_fxm->period = MIN(p_fxm->period + fxp, PERIOD_MAX); + p_osc->freq = FREQ(p_fxm->period); + } + break; +/* + // Just feels... ugly + case 0xE9: // Retrigger note + temp = tick; while(temp >= fxp) temp -= fxp; + if(!temp) { + if(ch == 3) { + p_osc->freq = p_osc->phase = 0x2000; + } else { + p_osc->phase = 0; + } + } + break; +*/ + case 0xEC: // Note cut + if(fxp == tick) p_osc->vol = 0x00; + break; + default: // Multi-effect processing + + // Portamento + if(ch != 3 && (fx == 0x30 || fx == 0x50)) { + if(p_fxm->period < p_fxm->port_target) p_fxm->period = MIN(p_fxm->period + p_fxm->port_speed, p_fxm->port_target); + else p_fxm->period = MAX(p_fxm->period - p_fxm->port_speed, p_fxm->port_target); + if(p_fxm->glissando) p_osc->freq = FREQ(glissando(ch)); + else p_osc->freq = FREQ(p_fxm->period); + } + + // Volume slide + if(fx == 0x50 || fx == 0x60 || fx == 0xA0) { + if((fxp & 0xF0) == 0) p_fxm->volume -= (LO4(fxp)); + if((fxp & 0x0F) == 0) p_fxm->volume += (HI4(fxp)); + p_osc->vol = p_fxm->volume = MAX(MIN(p_fxm->volume, 0x20), 0); + } + } + } + + // Normal play and arpeggio + if(fx == 0x00) { + if(ch != 3) { + temp = tick; while(temp > 2) temp -= 2; + if(temp == 0) { + + // Reset + p_osc->freq = FREQ(p_fxm->period); + } else if(fxp) { + + // Arpeggio + p_osc->freq = FREQ(arpeggio(ch, (temp == 1 ? HI4(fxp) : LO4(fxp)))); + } + } + } else if(fx == 0x40 || fx == 0x60) { + + // Vibrato + if(ch != 3) p_osc->freq = FREQ((p_fxm->period + do_osc(&p_fxm->vibr))); + } else if(fx == 0x70) { + int8_t trem = p_fxm->volume + do_osc(&p_fxm->trem); + p_osc->vol = MAX(MIN(trem, 0x20), 0); + } + + // Next channel + p_fxm++; p_cel++; p_osc++; + } + + // Advance tick + if(++tick == speed) tick = 0; + + // Advance playback + if(tick == 0) { + if(++ix_row == 64) { + ix_row = 0; + if(++ix_order >= order_count) ix_order = 0; + } + // Forced order/row + if( ix_nextorder != 0xFF ) { + ix_order = ix_nextorder; + ix_nextorder = 0xFF; + } + if( ix_nextrow != 0xFF ) { + ix_row = ix_nextrow; + ix_nextrow = 0xFF; + } + decrunch_row(); + } + + } + + lockout = false; +} \ No newline at end of file diff --git a/libraries/Robot_Control/Squawk.h b/libraries/Robot_Control/Squawk.h new file mode 100644 index 00000000000..3481acfa7e9 --- /dev/null +++ b/libraries/Robot_Control/Squawk.h @@ -0,0 +1,265 @@ +// Squawk Soft-Synthesizer Library for Arduino +// +// Davey Taylor 2013 +// d.taylor@arduino.cc + +#ifndef _SQUAWK_H_ +#define _SQUAWK_H_ +#include +#include +#include "Arduino.h" + +#define Melody const uint8_t PROGMEM + +class SquawkStream { + public: + virtual ~SquawkStream() = 0; + virtual uint8_t read() = 0; + virtual void seek(size_t offset) = 0; +}; +inline SquawkStream::~SquawkStream() { } + +class SquawkSynth { + +protected: + // Load and play specified melody + void play(SquawkStream *melody); + +public: + SquawkSynth() {}; + + // Initialize Squawk to generate samples at sample_rate Hz + void begin(uint16_t sample_rate); + + // Load and play specified melody + // melody needs to point to PROGMEM data + void play(const uint8_t *melody); + + // Resume currently loaded melody (or enable direct osc manipulation by sketch) + void play(); + + // Pause playback + void pause(); + + // Stop playback (unloads song) + void stop(); + + // Tune Squawk to a different frequency - default is 1.0 + void tune(float tuning); + + // Change the tempo - default is 50 + void tempo(uint16_t tempo); +}; + +extern SquawkSynth Squawk; + +// oscillator structure +typedef struct { + uint8_t vol; + uint16_t freq; + uint16_t phase; +} osc_t; + +typedef osc_t Oscillator; + +// oscillator memory +extern osc_t osc[4]; +extern uint8_t pcm; +// channel 0 is pulse wave @ 25% duty +// channel 1 is square wave +// channel 2 is triangle wave +// channel 3 is noise + +// For channel 3, freq is used as part of its LFSR and should not be changed. +// LFSR: Linear feedback shift register, a method of producing a +// pseudo-random bit sequence, used to generate nasty noise. + +#ifdef __AVR_ATmega32U4__ +// Supported configurations for ATmega32U4 +#define SQUAWK_PWM_PIN5 OCR3AL +#define SQUAWK_PWM_PIN11 OCR0A +#define SQUAWK_PWM_PIN3 OCR0B +/* +// NOT SUPPORTED YET +#define SQUAWK_PWM_PIN6 OCR4D +#define SQUAWK_PWM_PIN9 OCR4B +#define SQUAWK_PWM_PIN10 OCR4B +*/ +#endif + +#ifdef __AVR_ATmega168__ +// Supported configurations for ATmega168 +#define SQUAWK_PWM_PIN6 OCR0A +#define SQUAWK_PWM_PIN5 OCR0B +#define SQUAWK_PWM_PIN11 OCR2A +#define SQUAWK_PWM_PIN3 OCR2B +#endif + +#ifdef __AVR_ATmega328P__ +// Supported configurations for ATmega328P +#define SQUAWK_PWM_PIN6 OCR0A +#define SQUAWK_PWM_PIN5 OCR0B +#define SQUAWK_PWM_PIN11 OCR2A +#define SQUAWK_PWM_PIN3 OCR2B +#endif + +/* +// NOT SUPPORTED YET +#define SQUAWK_SPI SPDR +#define SQUAWK_RLD_PORTB PORTB +#define SQUAWK_RLD_PORTC PORTC +*/ + +extern void squawk_playroutine() asm("squawk_playroutine"); + +// SAMPLE GRINDER +// generates samples and updates oscillators +// uses 132 cycles (not counting playroutine) +// ~1/3 CPU @ 44kHz on 16MHz +#define SQUAWK_CONSTRUCT_ISR(TARGET_REGISTER) \ +uint16_t cia, cia_count; \ +intptr_t squawk_register = (intptr_t)&TARGET_REGISTER; \ +ISR(TIMER1_COMPA_vect, ISR_NAKED) { \ + asm volatile( \ + "push r2 " "\n\t" \ + "in r2, __SREG__ " "\n\t" \ + "push r18 " "\n\t" \ + "push r27 " "\n\t" \ + "push r26 " "\n\t" \ + "push r0 " "\n\t" \ + "push r1 " "\n\t" \ +\ + "lds r18, osc+2*%[mul]+%[fre] " "\n\t" \ + "lds r0, osc+2*%[mul]+%[pha] " "\n\t" \ + "add r0, r18 " "\n\t" \ + "sts osc+2*%[mul]+%[pha], r0 " "\n\t" \ + "lds r18, osc+2*%[mul]+%[fre]+1" "\n\t" \ + "lds r1, osc+2*%[mul]+%[pha]+1" "\n\t" \ + "adc r1, r18 " "\n\t" \ + "sts osc+2*%[mul]+%[pha]+1, r1 " "\n\t" \ +\ + "mov r27, r1 " "\n\t" \ + "sbrc r27, 7 " "\n\t" \ + "com r27 " "\n\t" \ + "lsl r27 " "\n\t" \ + "lds r26, osc+2*%[mul]+%[vol] " "\n\t" \ + "subi r27, 128 " "\n\t" \ + "muls r27, r26 " "\n\t" \ + "lsl r1 " "\n\t" \ + "mov r26, r1 " "\n\t" \ +\ + "lds r18, osc+0*%[mul]+%[fre] " "\n\t" \ + "lds r0, osc+0*%[mul]+%[pha] " "\n\t" \ + "add r0, r18 " "\n\t" \ + "sts osc+0*%[mul]+%[pha], r0 " "\n\t" \ + "lds r18, osc+0*%[mul]+%[fre]+1" "\n\t" \ + "lds r1, osc+0*%[mul]+%[pha]+1" "\n\t" \ + "adc r1, r18 " "\n\t" \ + "sts osc+0*%[mul]+%[pha]+1, r1 " "\n\t" \ +\ + "mov r18, r1 " "\n\t" \ + "lsl r18 " "\n\t" \ + "and r18, r1 " "\n\t" \ + "lds r27, osc+0*%[mul]+%[vol] " "\n\t" \ + "sbrc r18, 7 " "\n\t" \ + "neg r27 " "\n\t" \ + "add r26, r27 " "\n\t" \ +\ + "lds r18, osc+1*%[mul]+%[fre] " "\n\t" \ + "lds r0, osc+1*%[mul]+%[pha] " "\n\t" \ + "add r0, r18 " "\n\t" \ + "sts osc+1*%[mul]+%[pha], r0 " "\n\t" \ + "lds r18, osc+1*%[mul]+%[fre]+1" "\n\t" \ + "lds r1, osc+1*%[mul]+%[pha]+1" "\n\t" \ + "adc r1, r18 " "\n\t" \ + "sts osc+1*%[mul]+%[pha]+1, r1 " "\n\t" \ +\ + "lds r27, osc+1*%[mul]+%[vol] " "\n\t" \ + "sbrc r1, 7 " "\n\t" \ + "neg r27 " "\n\t" \ + "add r26, r27 " "\n\t" \ +\ + "ldi r27, 1 " "\n\t" \ + "lds r0, osc+3*%[mul]+%[fre] " "\n\t" \ + "lds r1, osc+3*%[mul]+%[fre]+1" "\n\t" \ + "add r0, r0 " "\n\t" \ + "adc r1, r1 " "\n\t" \ + "sbrc r1, 7 " "\n\t" \ + "eor r0, r27 " "\n\t" \ + "sbrc r1, 6 " "\n\t" \ + "eor r0, r27 " "\n\t" \ + "sts osc+3*%[mul]+%[fre], r0 " "\n\t" \ + "sts osc+3*%[mul]+%[fre]+1, r1 " "\n\t" \ +\ + "lds r27, osc+3*%[mul]+%[vol] " "\n\t" \ + "sbrc r1, 7 " "\n\t" \ + "neg r27 " "\n\t" \ + "add r26, r27 " "\n\t" \ +\ + "lds r27, pcm " "\n\t" \ + "add r26, r27 " "\n\t" \ + "sts %[reg], r26 " "\n\t" \ +\ + "lds r27, cia_count+1 " "\n\t" \ + "lds r26, cia_count " "\n\t" \ + "sbiw r26, 1 " "\n\t" \ + "breq call_playroutine " "\n\t" \ + "sts cia_count+1, r27 " "\n\t" \ + "sts cia_count, r26 " "\n\t" \ + "pop r1 " "\n\t" \ + "pop r0 " "\n\t" \ + "pop r26 " "\n\t" \ + "pop r27 " "\n\t" \ + "pop r18 " "\n\t" \ + "out __SREG__, r2 " "\n\t" \ + "pop r2 " "\n\t" \ + "reti " "\n\t" \ + "call_playroutine: " "\n\t" \ +\ + "lds r27, cia+1 " "\n\t" \ + "lds r26, cia " "\n\t" \ + "sts cia_count+1, r27 " "\n\t" \ + "sts cia_count, r26 " "\n\t" \ +\ + "sei " "\n\t" \ + "push r19 " "\n\t" \ + "push r20 " "\n\t" \ + "push r21 " "\n\t" \ + "push r22 " "\n\t" \ + "push r23 " "\n\t" \ + "push r24 " "\n\t" \ + "push r25 " "\n\t" \ + "push r30 " "\n\t" \ + "push r31 " "\n\t" \ +\ + "clr r1 " "\n\t" \ + "call squawk_playroutine " "\n\t" \ +\ + "pop r31 " "\n\t" \ + "pop r30 " "\n\t" \ + "pop r25 " "\n\t" \ + "pop r24 " "\n\t" \ + "pop r23 " "\n\t" \ + "pop r22 " "\n\t" \ + "pop r21 " "\n\t" \ + "pop r20 " "\n\t" \ + "pop r19 " "\n\t" \ +\ + "pop r1 " "\n\t" \ + "pop r0 " "\n\t" \ + "pop r26 " "\n\t" \ + "pop r27 " "\n\t" \ + "pop r18 " "\n\t" \ + "out __SREG__, r2 " "\n\t" \ + "pop r2 " "\n\t" \ + "reti " "\n\t" \ + : \ + : [reg] "M" _SFR_MEM_ADDR(TARGET_REGISTER), \ + [mul] "M" (sizeof(Oscillator)), \ + [pha] "M" (offsetof(Oscillator, phase)), \ + [fre] "M" (offsetof(Oscillator, freq)), \ + [vol] "M" (offsetof(Oscillator, vol)) \ + ); \ +} + +#endif \ No newline at end of file diff --git a/libraries/Robot_Control/SquawkSD.cpp b/libraries/Robot_Control/SquawkSD.cpp new file mode 100644 index 00000000000..3c97ef43a99 --- /dev/null +++ b/libraries/Robot_Control/SquawkSD.cpp @@ -0,0 +1,182 @@ +#include + +SquawkSynthSD SquawkSD; + +class StreamFile : public SquawkStream { + private: + Fat16 f; + public: + StreamFile(Fat16 file = Fat16()) { f = file; } + uint8_t read() { return f.read(); } + void seek(size_t offset) { f.seekSet(offset); } +}; + +static StreamFile file; + +extern uint16_t period_tbl[84] PROGMEM; + +void SquawkSynthSD::play(Fat16 melody) { + SquawkSynth::pause(); + file = StreamFile(melody); + SquawkSynth::play(&file); +} + +/* +void SquawkSynthSD::convert(Fat16 in, Fat16 out) { + unsigned int n; + uint8_t patterns = 0, order_count; + unsigned int ptn, row, chn; + uint8_t temp; + + uint8_t fxc[4], fxp[4], note[4], sample[4]; + uint16_t period; + + out.write('S'); // ID + out.write('Q'); + out.write('M'); + out.write('1'); + out.write((uint8_t)0); // No meta data + out.write((uint8_t)0); + + // Write order list, count patterns + in.seek(0x3B6); + order_count = in.read(); + out.write(order_count); + in.seek(0x3B8); + for(n = 0; n < order_count; n++) { + temp = in.read(); + if(temp >= patterns) patterns = temp + 1; + out.write(temp); + } + + // Write patterns + in.seek(0x43C); + for(ptn = 0; ptn < patterns; ptn++) { + for(row = 0; row < 64; row++) { + for(chn = 0; chn < 4; chn++) { + + // Basic extraction + temp = in.read(); // sample.msb and period.msb + period = (temp & 0x0F) << 8; + sample[chn] = temp & 0xF0; + period |= in.read(); // period.lsb + temp = in.read(); // sample.lsb and effect + sample[chn] |= temp >> 4; + fxc[chn] = (temp & 0x0F) << 4; + fxp[chn] = in.read(); // parameters + if(fxc[chn] == 0xE0) { + fxc[chn] |= fxp[chn] >> 4; // extended parameters + fxp[chn] &= 0x0F; + } + + #define DIF(A, B) ((A) > (B) ? ((int32_t)(A) - (int32_t)(B)) : ((int32_t)(B) - (int32_t)(A))) + // Find closest matching period + if(period == 0) { + note[chn] = 0x7F; + } else { + int16_t best = DIF(period, pgm_read_word(&period_tbl[0])); + note[chn] = 0; + for(n = 0; n < sizeof(period_tbl) / sizeof(uint16_t); n++) { + if(DIF(period, pgm_read_word(&period_tbl[n])) < best) { + note[chn] = n; + best = DIF(period, pgm_read_word(&period_tbl[n])); + } + } + } + + // Crunch volume/decimal commands + if(fxc[chn] == 0x50 || fxc[chn] == 0x60 || fxc[chn] == 0xA0) { + fxp[chn] = (fxp[chn] >> 1) & 0x77; + } else if(fxc[chn] == 0x70) { + fxp[chn] = (fxp[chn] & 0xF0) | ((fxp[chn] & 0x0F) >> 1); + } else if(fxc[chn] == 0xC0 || fxc[chn] == 0xEA || fxc[chn] == 0xEB) { + fxp[chn] >>= 1; + } else if(fxc[chn] == 0xD0) { + fxp[chn] = ((fxp[chn] >> 4) * 10) | (fxp[chn] & 0x0F); + } + + // Re-nibblify - it's a word! + if(chn != 3) { + if((fxc[chn] & 0xF0) == 0xE0) fxp[chn] |= fxc[chn] << 4; + fxc[chn] >>= 4; + } + + } + + // Ghetto crunch the last channel to save a byte + switch(fxc[3]) { + case 0x50: case 0x60: case 0xA0: + fxc[3] = 0x1; + if((fxp[3] >> 4) >= (fxp[3] & 0x0F)) { + fxp[3] = 0x80 + ((fxp[3] >> 4) - (fxp[3] & 0x0F)); + } else { + fxp[3] = ((fxp[3] & 0x0F) - (fxp[3] >> 4)); + } + break; + case 0x70: + fxc[3] = (fxp[3] & 0x4) ? 0x3 : 0x2; + fxp[3] = (fxp[3] >> 4) | ((fxp[3] & 0x03) << 4); + break; + case 0xC0: + fxc[3] = 0x4; + fxp[3] &= 0x1F; + break; + case 0xB0: + fxc[3] = 0x5; + fxp[3] &= 0x1F; + break; + case 0xD0: + fxc[3] = 0x6; + if(fxp[3] > 63) fxp[3] = 0; + break; + case 0xF0: + if(fxp[3] > 0x20) { + fxc[3] = 0x0; + fxp[3] = 0x00; + } else { + fxc[3] = 0x7; + } + break; + case 0xE7: + fxc[3] = 0x8; + break; + case 0xE9: + fxc[3] = 0x9; + break; + case 0xEA: + fxc[3] = 0xA; + fxp[3] |= 0x08; + break; + case 0xEB: + fxc[3] = 0xA; + break; + case 0xEC: + fxc[3] = 0xB; + break; + case 0xED: + fxc[3] = 0xB; + fxp[3] |= 0x10; + break; + case 0xEE: + fxc[3] = 0xC; + break; + default: + fxc[3] = 0; + fxp[3] = 0; + } + if(note[3] != 0x7F) fxp[3] |= 0x80; + if(sample[3]) fxp[3] |= 0x40; + + // Write out + out.write((fxc[0]) | fxc[1] << 4); + out.write(fxp[0]); + out.write(fxp[1]); + out.write((fxc[2]) | fxc[3] << 4); + out.write(fxp[2]); + out.write(fxp[3]); + out.write(note[0] | (sample[0] == 0 ? 0x00 : 0x80)); + out.write(note[1] | (sample[1] == 0 ? 0x00 : 0x80)); + out.write(note[2] | (sample[2] == 0 ? 0x00 : 0x80)); + } + } +}*/ \ No newline at end of file diff --git a/libraries/Robot_Control/SquawkSD.h b/libraries/Robot_Control/SquawkSD.h new file mode 100644 index 00000000000..89d46a59a25 --- /dev/null +++ b/libraries/Robot_Control/SquawkSD.h @@ -0,0 +1,17 @@ +#ifndef _SQUAWKSD_H_ +#define _SQUAWKSD_H_ +#include +#include "Fat16.h" + +class SquawkSynthSD : public SquawkSynth { + private: + Fat16 f; + public: + inline void play() { Squawk.play(); }; + void play(Fat16 file); + //void convert(Fat16 in, Fat16 out); +}; + +extern SquawkSynthSD SquawkSD; + +#endif \ No newline at end of file diff --git a/libraries/Robot_Control/communication.cpp b/libraries/Robot_Control/communication.cpp new file mode 100644 index 00000000000..eaf5346c4dd --- /dev/null +++ b/libraries/Robot_Control/communication.cpp @@ -0,0 +1 @@ +#include bool RobotControl::isActionDone(){ if(messageIn.receiveData()){ if(messageIn.readByte()==COMMAND_ACTION_DONE){ return true; } } return false; } void RobotControl::pauseMode(uint8_t onOff){ messageOut.writeByte(COMMAND_PAUSE_MODE); if(onOff){ messageOut.writeByte(true); }else{ messageOut.writeByte(false); } messageOut.sendData(); } void RobotControl::lineFollowConfig(uint8_t KP, uint8_t KD, uint8_t robotSpeed, uint8_t intergrationTime){ messageOut.writeByte(COMMAND_LINE_FOLLOW_CONFIG); messageOut.writeByte(KP); messageOut.writeByte(KD); messageOut.writeByte(robotSpeed); messageOut.writeByte(intergrationTime); messageOut.sendData(); } \ No newline at end of file diff --git a/libraries/Robot_Control/examples/explore/R01_Logo/R01_Logo.ino b/libraries/Robot_Control/examples/explore/R01_Logo/R01_Logo.ino new file mode 100644 index 00000000000..41936778afd --- /dev/null +++ b/libraries/Robot_Control/examples/explore/R01_Logo/R01_Logo.ino @@ -0,0 +1,136 @@ +/* Robot Logo + + This sketch demonstrates basic movement of the Robot. + When the sketch starts, press the on-board buttons to tell + the robot how to move. Pressing the middle button will + save the pattern, and the robot will follow accordingly. + You can record up to 20 commands. The robot will move for + one second per command. + + This example uses images on an SD card. It looks for + files named "lg0.bmp" and "lg1.bmp" and draws them on the + screen. + + Circuit: + * Arduino Robot + + created 1 May 2013 + by X. Yang + modified 12 May 2013 + by D. Cuartielles + + This example is in the public domain + */ + +#include // include the robot library +#include +#include + +int commands[20]; // array for storing commands + +void setup() { + // initialize the Robot, SD card, and display + Robot.begin(); + Robot.beginTFT(); + Robot.beginSD(); + + // draw "lg0.bmp" and "lg1.bmp" on the screen + Robot.displayLogos(); +} + +void loop() { + + Robot.drawBMP("intro.bmp", 0, 0); //display background image + + iniCommands(); // remove commands from the array + addCommands(); // add commands to the array + + delay(1000); // wait for a second + + executeCommands(); // follow orders + + Robot.stroke(0,0,0); + Robot.text("Done!", 5, 103); // write some text to the display + delay(1500); // wait for a moment +} + +// empty the commands array +void iniCommands() { + for(int i=0; i<20; i++) + commands[i]=-1; +} + +// add commands to the array +void addCommands() { + Robot.stroke(0,0,0); + // display text on the screen + Robot.text("1. Press buttons to\n add commands.\n\n 2. Middle to finish.", 5, 5); + + // read the buttons' state + for(int i=0; i<20;) { //max 20 commands + int key = Robot.keyboardRead(); + if(key == BUTTON_MIDDLE) { //finish input + break; + }else if(key == BUTTON_NONE) { //if no button is pressed + continue; + } + commands[i] = key; // save the button to the array + PrintCommandI(i, 46); // print the command on the screen + delay(100); + i++; + } +} + +// run through the array and move the robot +void executeCommands() { + // print status to the screen + Robot.text("Excuting...",5,70); + + // read through the array and move accordingly + for(int i=0; i<20; i++) { + switch(commands[i]) { + case BUTTON_LEFT: + Robot.turn(-90); + break; + case BUTTON_RIGHT: + Robot.turn(90); + break; + case BUTTON_UP: + Robot.motorsWrite(255, 255); + break; + case BUTTON_DOWN: + Robot.motorsWrite(-255, -255); + break; + case BUTTON_NONE: + return; + } + // print the current command to the screen + Robot.stroke(255,0,0); + PrintCommandI(i, 86); + delay(1000); + + // stop moving for a second + Robot.motorsStop(); + delay(1000); + } +} + +// convert the button press to a single character +char keyToChar(int key) { + switch(key) { + case BUTTON_LEFT: + return '<'; + case BUTTON_RIGHT: + return '>'; + case BUTTON_UP: + return '^'; + case BUTTON_DOWN: + return 'v'; + } +} + +// display a command +void PrintCommandI(int i, int originY) { + Robot.text(keyToChar(commands[i]), i%14*8+5, i/14*10+originY); +} + diff --git a/libraries/Robot_Control/examples/explore/R02_Line_Follow/R02_Line_Follow.ino b/libraries/Robot_Control/examples/explore/R02_Line_Follow/R02_Line_Follow.ino new file mode 100644 index 00000000000..809cc38e177 --- /dev/null +++ b/libraries/Robot_Control/examples/explore/R02_Line_Follow/R02_Line_Follow.ino @@ -0,0 +1,75 @@ +/* Robot Line Follow + + This sketch demonstrates the line following capabilities + of the Arduino Robot. On the floor, place some black + electrical tape along the path you wish the robot to follow. + To indicate a stopping point, place another piece of tape + perpendicular to the path. + + Circuit: + * Arduino Robot + + created 1 May 2013 + by X. Yang + modified 12 May 2013 + by D. Cuartielles + + This example is in the public domain + */ + +#include // include the robot library +#include +#include + +long timerOrigin; // used for counting elapsed time + +void setup() { + // initialize the Robot, SD card, display, and speaker + Robot.begin(); + Robot.beginTFT(); + Robot.beginSD(); + Robot.beginSpeaker(); + + // show the logots on the TFT screen + Robot.displayLogos(); + + Robot.drawBMP("lf.bmp", 0, 0); // display background image + + Robot.playFile("chase.sqm"); // play a song from the SD card + + // add the instructions + Robot.text("Line Following\n\n place the robot on\n the track and \n see it run", 5, 5); + Robot.text("Press the middle\n button to start...", 5, 61); + Robot.waitContinue(); + + // These are some general values that work for line following + // uncomment one or the other to see the different behaviors of the robot + // Robot.lineFollowConfig(11, 5, 50, 10); + Robot.lineFollowConfig(11, 7, 60, 5); + + //set the motor board into line-follow mode + Robot.setMode(MODE_LINE_FOLLOW); + + // start + Robot.fill(255, 255, 255); + Robot.stroke(255, 255, 255); + Robot.rect(0, 0, 128, 80); // erase the previous text + Robot.stroke(0, 0, 0); + Robot.text("Start", 5, 5); + + Robot.stroke(0, 0, 0); // choose color for the text + Robot.text("Time passed:", 5, 21); // write some text to the screen + + timerOrigin=millis(); // keep track of the elapsed time + + while(!Robot.isActionDone()) { //wait for the finish signal + Robot.debugPrint(millis()-timerOrigin, 5, 29); // show how much time has passed + } + + Robot.stroke(0, 0, 0); + Robot.text("Done!", 5, 45); +} +void loop() { + //nothing here, the program only runs once. Reset the robot + //to do it again! +} diff --git a/libraries/Robot_Control/examples/explore/R03_Disco_Bot/R03_Disco_Bot.ino b/libraries/Robot_Control/examples/explore/R03_Disco_Bot/R03_Disco_Bot.ino new file mode 100644 index 00000000000..29c1d5eb94e --- /dev/null +++ b/libraries/Robot_Control/examples/explore/R03_Disco_Bot/R03_Disco_Bot.ino @@ -0,0 +1,181 @@ +/* Disco Bot + + This sketch shows you how to use the melody playing + feature of the robot, with some really cool 8-bit music. + Music will play when the robot is turned on, and it + will show you some dance moves. + + Circuit: + * Arduino Robot + + created 1 May 2013 + by X. Yang + modified 12 May 2013 + by D. Cuartielles + + This example is in the public domain + */ + +#include // include the robot library +#include +#include + +/* Dancing steps: + S: stop + L: turn left + R: turn right + F: go forward + B: go backwards + + The number after each command determines how long + each step lasts. Each number is 1/2 second long. + + The "\0" indicates end of string +*/ +char danceScript[] = "S4L1R1S2F1B1S1\0"; + +int currentScript = 0; // what step are we at + +int currentSong = 0; // keep track of the current song +static const int SONGS_COUNT = 3; // number of songs + +// an array to hold the songs +char musics[][11] = { + "melody.sqm", + "menu.sqm", + "chase.sqm", +}; + +// variables for non-blocking delay +long waitFrom; +long waitTime = 0; + +void setup() { + // initialize the Robot, SD card, display, and speaker + Robot.begin(); + Robot.beginSpeaker(); + Robot.beginSD(); + Robot.beginTFT(); + + // draw "lg0.bmp" and "lg1.bmp" on the screen + Robot.displayLogos(); + + // Print instructions to the screen + Robot.text("1. Use left and\n right key to switch\n song", 5, 5); + Robot.text("2. Put robot on the\n ground to dance", 5, 33); + + // wait for a few soconds + delay(3000); + + setInterface(); // display the current song + play(0); //play the first song in the array + + resetWait(); //Initialize non-blocking delay +} + +void loop() { + // read the butttons on the robot + int key = Robot.keyboardRead(); + + // Right/left buttons play next/previous song + switch(key) { + case BUTTON_UP: + case BUTTON_LEFT: + play(-1); //play previous song + break; + case BUTTON_DOWN: + case BUTTON_RIGHT: + play(1); //play next song + break; + } + + // dance! + runScript(); +} + +// Dancing function +void runScript() { + if(!waiting()) { // if the previous instructions have finished + // get the next 2 commands (direction and duration) + parseCommand(danceScript[currentScript], danceScript[currentScript+1]); + currentScript += 2; + if(danceScript[currentScript] == '\0') // at the end of the array + currentScript = 0; // start again at the beginning + } +} + +// instead of delay, use this timer +boolean waiting() { + if(millis()-waitFrom >= waitTime) + return false; + else + return true; +} + +// how long to wait +void wait(long t) { + resetWait(); + waitTime = t; +} + +// reset the timer +void resetWait() { + waitFrom = millis(); +} + +// read the direction and dirstion of the steps +void parseCommand(char dir, char duration) { + //convert the scripts to action + switch(dir) { + case 'L': + Robot.motorsWrite(-255, 255); + break; + case 'R': + Robot.motorsWrite(255, -255); + break; + case 'F': + Robot.motorsWrite(255, 255); + break; + case 'B': + Robot.motorsWrite(-255, -255); + break; + case 'S': + Robot.motorsStop(); + break; + } + //You can change "500" to change the pace of dancing + wait(500*(duration-'0')); +} + +// display the song +void setInterface() { + Robot.clearScreen(); + Robot.stroke(0, 0, 0); + Robot.text(musics[0], 0, 0); +} + +// display the next song +void select(int seq, boolean onOff) { + if(onOff){//select + Robot.stroke(0, 0, 0); + Robot.text(musics[seq], 0, 0); + }else{//deselect + Robot.stroke(255, 255, 255); + Robot.text(musics[seq], 0, 0); + } +} + +// play the slected song +void play(int seq) { + select(currentSong, false); + if(currentSong <= 0 && seq == -1) { //previous of 1st song? + currentSong = SONGS_COUNT-1; //go to last song + } else if(currentSong >= SONGS_COUNT-1 && seq == 1) { //next of last? + currentSong = 0; //go to 1st song + } else { + currentSong += seq; //next song + } + Robot.stopPlayFile(); + Robot.playFile(musics[currentSong]); + select(currentSong, true); //display the current song +} diff --git a/libraries/Robot_Control/examples/explore/R04_Compass/R04_Compass.ino b/libraries/Robot_Control/examples/explore/R04_Compass/R04_Compass.ino new file mode 100644 index 00000000000..513d85d9082 --- /dev/null +++ b/libraries/Robot_Control/examples/explore/R04_Compass/R04_Compass.ino @@ -0,0 +1,72 @@ +/* Robot Compass + + The robot has an on-board compass module, with + which it can tell the direction the robot is + facing. This sketch will make sure the robot + goes towards a certain direction. + + Beware, magnets will interfere with the compass + readings. + + Circuit: + * Arduino Robot + + created 1 May 2013 + by X. Yang + modified 12 May 2013 + by D. Cuartielles + + This example is in the public domain + */ + +// include the robot library +#include +#include +#include + +int speedLeft; +int speedRight; +int compassValue; +int direc = 180; //Direction the robot is heading + +void setup() { + // initialize the modules + Robot.begin(); + Robot.beginTFT(); + Robot.beginSD(); + Robot.displayLogos(); +} + +void loop() { + // read the compass orientation + compassValue = Robot.compassRead(); + + // how many degrees are we off + int diff = compassValue-direc; + + // modify degress + if(diff > 180) + diff = -360+diff; + else if(diff < -180) + diff = 360+diff; + + // Make the robot turn to its proper orientation + diff = map(diff, -180, 180, -255, 255); + + if(diff > 0) { + // keep the right wheel spinning, + // change the speed of the left wheel + speedLeft = 255-diff; + speedRight = 255; + } else { + // keep the right left spinning, + // change the speed of the left wheel + speedLeft = 255; + speedRight = 255+diff; + } + // write out to the motors + Robot.motorsWrite(speedLeft, speedRight); + + // draw the orientation on the screen + Robot.drawCompass(compassValue); +} diff --git a/libraries/Robot_Control/examples/explore/R05_Inputs/R05_Inputs.ino b/libraries/Robot_Control/examples/explore/R05_Inputs/R05_Inputs.ino new file mode 100644 index 00000000000..43b3f2b9e26 --- /dev/null +++ b/libraries/Robot_Control/examples/explore/R05_Inputs/R05_Inputs.ino @@ -0,0 +1,167 @@ +/* Robot Inputs + + This sketch shows you how to use the on-board + potentiometer and buttons as inputs. + + Turning the potentiometer draws a clock-shaped + circle. The up and down buttons change the pitch, + while the left and right buttons change the tempo. + The middle button resets tempo and pitch. + + Circuit: + * Arduino Robot + + created 1 May 2013 + by X. Yang + modified 12 May 2013 + by D. Cuartielles + + This example is in the public domain + */ + +#include +#include +#include + +// default tempo and pitch of the music +int tempo = 60; +int pitch = 1000; + +void setup() { + // initialize the Robot, SD card, speaker, and display + Robot.begin(); + Robot.beginTFT(); + Robot.beginSpeaker(); + Robot.beginSD(); + + // draw "lg0.bmp" and "lg1.bmp" on the screen + Robot.displayLogos(); + + // play a sound file + Robot.playFile("Melody.sqm"); +} + +void loop() { + // check the value of the buttons + keyDown(Robot.keyboardRead()); + + // check the value of the pot + drawKnob(Robot.knobRead()); +} + +// Draw the basic interface +void renderUI() { + //fill the buttons blank + Robot.fill(255, 255, 255); + Robot.rect(53, 58, 13, 13); // left + Robot.rect(93, 58, 13, 13); // right + Robot.rect(73, 38, 13, 13); // up + Robot.circle(79, 64, 6); // middle + Robot.rect(73, 78, 13, 13); // down + + //draw the knob + Robot.noFill(); + Robot.circle(26, 116, 17); // knob + + //draw the vertical bargraph + int fullPart=map(pitch, 200, 2000, 0, 58); //length of filled bargraph + Robot.fill(255, 255, 255); + Robot.rect(21, 30, 13, 58-fullPart); + Robot.fill(0, 0, 255); + Robot.rect(21, 88-fullPart, 13, fullPart); //58-fullPart+30 + + //draw the horizontal bargraph + fullPart = map(tempo, 20, 100, 0, 58); // length of filled bargraph + Robot.fill(255, 190, 0); + Robot.rect(53, 110, fullPart, 13); + Robot.fill(255, 255, 255); + Robot.rect(53+fullPart, 110, 58-fullPart, 13); +} + +void keyDown(int keyCode) { + // use a static int so it is persistent over time + static int oldKey; + switch(keyCode) { + case BUTTON_LEFT: + //left button pressed, reduces tempo + tempo -= 5; + if(tempo < 20) tempo = 20; //lowest tempo 20 + Robot.fill(255,190,0); + + Robot.rect(53, 58, 13, 13); + break; + case BUTTON_RIGHT: + //right button pressed, increases tempo + tempo += 5; + if(tempo > 100) tempo = 100; //highest tempo 100 + Robot.fill(255,190,0); + Robot.rect(93, 58, 13, 13); + break; + case BUTTON_UP: + //up button pressed, increases pitch + pitch += 120; + if(pitch > 2000) pitch = 2000; + Robot.fill(0, 0, 255); + + Robot.rect(73, 38, 13, 13); + break; + case BUTTON_DOWN: + //down button pressed, reduces pitch + pitch -= 120; + if(pitch < 200){ + pitch = 200; + } + Robot.fill(0, 0, 255); + + Robot.rect(73, 78, 13, 13); + break; + case BUTTON_MIDDLE: + //middle button pressed, resets tempo and pitch + tempo = 60; + pitch = 1000; + Robot.fill(160,160,160); + + Robot.circle(79, 64, 6); + break; + case BUTTON_NONE: + //Only when the keys are released(thus BUTTON_NONE is + //encountered the first time), the interface will be + //re-drawn. + if(oldKey != BUTTON_NONE){ + renderUI(); + } + break; + } + if(oldKey != keyCode) { + // change the song's tempo + Robot.tempoWrite(tempo); + // change the song's pitch + Robot.tuneWrite(float(pitch/1000.0)); + } + oldKey = keyCode; +} + +//Draw a circle according to value +//of the knob. +void drawKnob(int val) { + static int val_old; + int r=map(val,0,1023,1,15); + + //Only updates when the + //value changes. + if(val_old!=r){ + Robot.noFill(); + + //erase the old circle + Robot.stroke(255, 255, 255); + Robot.circle(26,116,r+1); + + //draw the new circle + Robot.stroke(255, 0, 255); + Robot.circle(26,116,r); + + Robot.stroke(0, 0, 0); + + val_old=r; + } +} diff --git a/libraries/Robot_Control/examples/explore/R06_Wheel_Calibration/R06_Wheel_Calibration.ino b/libraries/Robot_Control/examples/explore/R06_Wheel_Calibration/R06_Wheel_Calibration.ino new file mode 100644 index 00000000000..a3a2f53cfe9 --- /dev/null +++ b/libraries/Robot_Control/examples/explore/R06_Wheel_Calibration/R06_Wheel_Calibration.ino @@ -0,0 +1,40 @@ +/* 6 Wheel Calibration +* +* Use this sketch to calibrate the wheels in your robot. +* Your robot should drive as straight as possible when +* putting both motors at the same speed. +* +* Run the software and follow the on-screen instructions. +* Use the trimmer on the bottom board to make sure the +* robot is working at its best! +* +* (c) 2013 X. Yang +*/ +#include "scripts_library.h" + +#include +#include +#include + +void setup(){ + Serial.begin(9600); + Robot.begin(); + Robot.beginTFT(); + Robot.beginSD(); + + Robot.setTextWrap(false); + Robot.displayLogos(); + + writeAllScripts(); + +} +void loop(){ + int val=map(Robot.knobRead(),0,1023,-255,255); + Serial.println(val); + Robot.motorsWrite(val,val); + + int WC=map(Robot.trimRead(),0,1023,-20,20); + Robot.debugPrint(WC,108,149); + delay(40); + +} diff --git a/libraries/Robot_Control/examples/explore/R06_Wheel_Calibration/scripts_library.h b/libraries/Robot_Control/examples/explore/R06_Wheel_Calibration/scripts_library.h new file mode 100644 index 00000000000..cc5a80879b9 --- /dev/null +++ b/libraries/Robot_Control/examples/explore/R06_Wheel_Calibration/scripts_library.h @@ -0,0 +1,43 @@ +#include +#include + +prog_char script1[] PROGMEM="Wheel Calibration\n"; +prog_char script2[] PROGMEM="1. Put Robot on a flat surface\n"; +prog_char script3[] PROGMEM="2. Adjust speed with the knob on top\n"; +prog_char script4[] PROGMEM="3. If robot goes straight, it's done\n"; +prog_char script5[] PROGMEM="4. Use screwdriver on the trim on bottom\n"; +prog_char script6[] PROGMEM="Robot turns left, screw it clockwise;\n"; +prog_char script7[] PROGMEM="Turns right, screw it ct-colockwise;\n"; +prog_char script8[] PROGMEM="5. Repeat 4 until going straight\n"; + +char buffer[42];//must be longer than text + +PROGMEM const char *scripts[]={ + script1, + script2, + script3, + script4, + script5, + script6, + script7, + script8, +}; + +void getPGMtext(int seq){ + strcpy_P(buffer,(char*)pgm_read_word(&(scripts[seq]))); +} + +void writePGMtext(int seq){ + getPGMtext(seq); + Robot.print(buffer); +} + +void writeScript(int seq){ + writePGMtext(seq); +} + +void writeAllScripts(){ + for(int i=0;i<8;i++){ + writeScript(i); + } +} diff --git a/libraries/Robot_Control/examples/explore/R07_Runaway_Robot/R07_Runaway_Robot.ino b/libraries/Robot_Control/examples/explore/R07_Runaway_Robot/R07_Runaway_Robot.ino new file mode 100644 index 00000000000..ceab7dbd35a --- /dev/null +++ b/libraries/Robot_Control/examples/explore/R07_Runaway_Robot/R07_Runaway_Robot.ino @@ -0,0 +1,80 @@ +/* Runaway Robot + + Play tag with your robot! With an ultrasonic + distance sensor, it's capable of detecting and avoiding + obstacles, never bumping into walls again! + + You'll need to attach an untrasonic range finder to M1. + + Circuit: + * Arduino Robot + * US range finder like Maxbotix EZ10, with analog output + + created 1 May 2013 + by X. Yang + modified 12 May 2013 + by D. Cuartielles + + This example is in the public domain + */ + +// include the robot library +#include +#include +#include + +int sensorPin = M1; // pin is used by the sensor + +void setup() { + // initialize the Robot, SD card, and display + Serial.begin(9600); + Robot.begin(); + Robot.beginTFT(); + Robot.beginSD(); + Robot.displayLogos(); + + // draw a face on the LCD screen + setFace(true); +} + +void loop() { + // If the robot is blocked, turn until free + while(getDistance() < 40) { // If an obstacle is less than 20cm away + setFace(false); //shows an unhappy face + Robot.motorsStop(); // stop the motors + delay(1000); // wait for a moment + Robot.turn(90); // turn to the right and try again + setFace(true); // happy face + } + // if there are no objects in the way, keep moving + Robot.motorsWrite(255, 255); + delay(100); +} + +// return the distance in cm +float getDistance() { + // read the value from the sensor + int sensorValue = Robot.analogRead(sensorPin); + //Convert the sensor input to cm. + float distance_cm = sensorValue*1.27; + return distance_cm; +} + +// make a happy or sad face +void setFace(boolean onOff) { + if(onOff) { + // if true show a happy face + Robot.background(0, 0, 255); + Robot.setCursor(44, 60); + Robot.stroke(0, 255, 0); + Robot.setTextSize(4); + Robot.print(":)"); + }else{ + // if false show an upset face + Robot.background(255, 0, 0); + Robot.setCursor(44, 60); + Robot.stroke(0, 255, 0); + Robot.setTextSize(4); + Robot.print("X("); + } +} diff --git a/libraries/Robot_Control/examples/explore/R08_Remote_Control/R08_Remote_Control.ino b/libraries/Robot_Control/examples/explore/R08_Remote_Control/R08_Remote_Control.ino new file mode 100644 index 00000000000..ecf469f6c55 --- /dev/null +++ b/libraries/Robot_Control/examples/explore/R08_Remote_Control/R08_Remote_Control.ino @@ -0,0 +1,93 @@ +/* 08 Remote Control + + If you connect a IR receiver to the robot, + you can control it like a RC car. + Using the remote control comes with sensor + pack, You can make the robot move around + without even touching it! + + Circuit: + * Arduino Robot + * Connect the IRreceiver to D2 + * Remote control from Robot sensor pack + + based on the IRremote library + by Ken Shirriff + http://arcfn.com + + created 1 May 2013 + by X. Yang + modified 12 May 2013 + by D. Cuartielles + + This example is in the public domain + */ + +// include the necessary libraries +#include +#include +#include +#include +#include + +// Define a few commands from your remote control +#define IR_CODE_FORWARD 284154405 +#define IR_CODE_BACKWARDS 284113605 +#define IR_CODE_TURN_LEFT 284129925 +#define IR_CODE_TURN_RIGHT 284127885 +#define IR_CODE_CONTINUE -1 + +boolean isActing=false; //If the robot is executing command from remote +long timer; +const long TIME_OUT=150; + +void setup() { + // initialize the Robot, SD card, display, and speaker + Serial.begin(9600); + Robot.begin(); + Robot.beginTFT(); + Robot.beginSD(); + + // print some text to the screen + beginIRremote(); // Start the receiver +} + +void loop() { + // if there is an IR command, process it + if (IRrecived()) { + processResult(); + resumeIRremote(); // resume receiver + } + + //If the robot does not receive any command, stop it + if(isActing && (millis()-timer>=TIME_OUT)){ + Robot.motorsStop(); + isActing=false; + } +} +void processResult() { + unsigned long res = getIRresult(); + switch(res){ + case IR_CODE_FORWARD: + changeAction(1,1); //Move the robot forward + break; + case IR_CODE_BACKWARDS: + changeAction(-1,-1); //Move the robot backwards + break; + case IR_CODE_TURN_LEFT: + changeAction(-0.5,0.5); //Turn the robot left + break; + case IR_CODE_TURN_RIGHT: + changeAction(0.5,-0.5); //Turn the robot Right + break; + case IR_CODE_CONTINUE: + timer=millis(); //Continue the last action, reset timer + break; + } +} +void changeAction(float directionLeft, float directionRight){ + Robot.motorsWrite(255*directionLeft, 255*directionRight); + timer=millis(); + isActing=true; +} + diff --git a/libraries/Robot_Control/examples/explore/R09_Picture_Browser/R09_Picture_Browser.ino b/libraries/Robot_Control/examples/explore/R09_Picture_Browser/R09_Picture_Browser.ino new file mode 100644 index 00000000000..ebfcd4c2f82 --- /dev/null +++ b/libraries/Robot_Control/examples/explore/R09_Picture_Browser/R09_Picture_Browser.ino @@ -0,0 +1,161 @@ +/* Picture Browser + + You can make your own gallery/picture show with the + Robot. Put some pictures on the SD card, start the + sketch, they will diplay on the screen. + + Use the left/right buttons to navigate through the + previous and next images. + + Press up or down to enter a mode where you change + the pictures by rotating the robot. + + You can add your own pictures onto the SD card, and + view them in the Robot's gallery! + + Pictures must be uncompressed BMP, 24-bit color depth, + 160 pixels wide, and 128 pixels tall. + + They should be named as "picN.bmp". Replace 'N' with a + number between 0 and 9. + + The current code only supports 10 pictures. How would you + improve it to handle more? + + Circuit: + * Arduino Robot + + created 1 May 2013 + by X. Yang + modified 12 May 2013 + by D. Cuartielles + + This example is in the public domain + */ + +#include // include the robot library +#include +#include + +const int NUM_PICS = 4; //Total number of pictures in Gallery + +// name the modes +const int CONTROL_MODE_KEY = 0; +const int CONTROL_MODE_COMPASS = 1; + +char buffer[] = "pic1.bmp"; // current file name +int i = 1; // Current gallery sequence counter +int mode = 0; // Current mode + +// text to display on screen +char modeNames[][9] = { "keyboard", "tilt " }; + +void setup() { + // initialize the Robot, SD card, display, and speaker + Robot.beginSD(); + Robot.beginTFT(); + Robot.begin(); + + // draw "lg0.bmp" and "lg1.bmp" on the screen + Robot.displayLogos(); + + // draw init3.bmp from the SD card on the screen + Robot.drawBMP("init3.bmp", 0, 0); + + // display instructions + Robot.stroke(0, 0, 0); + Robot.text("The gallery\n\n has 2 modes, in\n keyboard mode, L/R\n key for switching\n pictures, U/D key\n for changing modes", 5, 5); + delay(6000); + Robot.clearScreen(); + Robot.drawBMP("pb.bmp", 0, 0); + Robot.text("In tilt mode,\n quickly tilt the\n robot to switch\n pictures", 5, 5); + delay(4000); +} + +void loop() { + buffer[3] = '0'+i;// change filename of the img to be displayed + Robot.drawBMP(buffer, 0, 0); // draw the file on the screen + // change control modes + switch(mode) { + case CONTROL_MODE_COMPASS: + compassControl(3); + break; + case CONTROL_MODE_KEY: + keyboardControl(); + break; + } + delay(200); +} + +void keyboardControl() { + //Use buttons to control the gallery + while(true) { + int keyPressed = Robot.keyboardRead(); // read the button values + switch(keyPressed) { + case BUTTON_LEFT: // display previous picture + if(--i < 1) i = NUM_PICS; + return; + case BUTTON_MIDDLE: // do nothing + case BUTTON_RIGHT: // display next picture + if(++i > NUM_PICS) i = 1; + return; + case BUTTON_UP: // change mode + changeMode(-1); + return; + case BUTTON_DOWN: // change mode + changeMode(1); + return; + } + } +} + +// if controlling by the compass +void compassControl(int change) { + // Rotate the robot to change the pictures + while(true) { + // read the value of the compass + int oldV = Robot.compassRead(); + + //get the change of angle + int diff = Robot.compassRead()-oldV; + if(diff > 180) diff -= 360; + else if(diff < -180) diff += 360; + + if(abs(diff) > change) { + if(++i > NUM_PICS) i = 1; + return; + } + + // chage modes, if buttons are pressed + int keyPressed = Robot.keyboardRead(); + switch(keyPressed) { + case BUTTON_UP: + changeMode(-1); + return; + case BUTTON_DOWN: + changeMode(1); + return; + } + delay(10); + } +} + +// Change the control mode and display it on the LCD +void changeMode(int changeDir) { + // alternate modes + mode += changeDir; + if(mode < 0) { + mode = 1; + } else if(mode > 1) + mode=0; + + // display the mode on screen + Robot.fill(255, 255, 255); + Robot.stroke(255, 255, 255); + Robot.rect(0, 0, 128, 12); + Robot.stroke(0, 0, 0); + Robot.text("Control:", 2, 2); + Robot.text(modeNames[mode], 52, 2); + delay(1000); +} + diff --git a/libraries/Robot_Control/examples/explore/R10_Rescue/R10_Rescue.ino b/libraries/Robot_Control/examples/explore/R10_Rescue/R10_Rescue.ino new file mode 100644 index 00000000000..77b639a337b --- /dev/null +++ b/libraries/Robot_Control/examples/explore/R10_Rescue/R10_Rescue.ino @@ -0,0 +1,121 @@ +/* Robot Rescue + + In this example, the robot enters the line following mode and + plays some music until it reaches its target. Once it finds the + target, it pushes it out of the track. It then returns to the + track and looks for a second target. + + You can make the robot push as many objects as you want to, just + add more to calls to the rescue function or even move that code + into the loop. + + Circuit: + * Arduino Robot + * some objects for the robot to push + * a line-following circuit + + created 1 May 2013 + by X. Yang + modified 12 May 2013 + by D. Cuartielles + + This example is in the public domain + */ + +#include // include the robot library +#include +#include + +void setup(){ + // initialize the Robot, SD card, display, and speaker + Robot.begin(); + Robot.beginTFT(); + Robot.beginSD(); + Robot.beginSpeaker(); + + // draw "lg0.bmp" and "lg1.bmp" on the screen + Robot.displayLogos(); + + // display the line following instructional image from the SD card + Robot.drawBMP("lf.bmp", 0, 0); + + // play the chase music file + Robot.playFile("chase.sqm"); + + // add the instructions + Robot.text("Rescue\n\n place the robot on\n the rescue track\n pushing the\n obstacles away", 5, 5); + Robot.text("Press the middle\n button to start...", 5, 61); + Robot.waitContinue(); + + // start + Robot.fill(255, 255, 255); + Robot.stroke(255, 255, 255); + Robot.rect(0, 0, 128, 80); // erase the previous text + Robot.stroke(0, 0, 0); + Robot.text("Start", 5, 5); + + // use this to calibrate the line following algorithm + // uncomment one or the other to see the different behaviors of the robot + // Robot.lineFollowConfig(11, 5, 50, 10); + Robot.lineFollowConfig(11, 7, 60, 5); + + // run the rescue sequence + rescueSequence(); + // find the track again + goToNext(); + // run the rescue sequence a second time + rescueSequence(); + + // here you could go on ... + + +} + +void loop(){ + //nothing here, the program only runs once. +} + +// run the sequence +void rescueSequence(){ + //set the motor board into line-follow mode + Robot.setMode(MODE_LINE_FOLLOW); + + while(!Robot.isActionDone()){ // wait until it is no longer following the line + } + delay(1000); + + // do the rescue operation + doRescue(); + delay(1000); +} + +void doRescue(){ + // Reached the endline, engage the target + Robot.motorsWrite(200,200); + delay(250); + Robot.motorsStop(); + delay(1000); + + // Turn the robot + Robot.turn(90); + Robot.motorsStop(); + delay(1000); + + // Move forward + Robot.motorsWrite(200,200); + delay(500); + Robot.motorsStop(); + delay(1000); + + // move backwards, leave the target + Robot.motorsWrite(-200,-200); + delay(500); + Robot.motorsStop(); +} + +void goToNext(){ + // Turn the robot + Robot.turn(-90); + Robot.motorsStop(); + delay(1000); +} diff --git a/libraries/Robot_Control/examples/explore/R11_Hello_User/R11_Hello_User.ino b/libraries/Robot_Control/examples/explore/R11_Hello_User/R11_Hello_User.ino new file mode 100644 index 00000000000..a30351ea3fa --- /dev/null +++ b/libraries/Robot_Control/examples/explore/R11_Hello_User/R11_Hello_User.ino @@ -0,0 +1,180 @@ +/* Hello User + + Hello User! This sketch is the first thing you see + when starting this robot. It gives you a warm welcome, + showing you some of the really amazing abilities of + the robot, and make itself really personal to you. + + Circuit: + * Arduino Robot + + created 1 May 2013 + by X. Yang + modified 12 May 2013 + by D. Cuartielles + + This example is in the public domain + */ + +#include // include the robot library +#include +#include + +// include the utility function for ths sketch +// see the details below +#include + +char buffer[20];//for storing user name + +void setup(){ + //necessary initialization sequence + Robot.begin(); + Robot.beginTFT(); + Robot.beginSD(); + + // show the logos from the SD card + Robot.displayLogos(); + + // clear the screen + Robot.clearScreen(); + + // From now on, display different slides of + // text/pictures in sequence. The so-called + // scripts are strings of text stored in the + // robot's memory + + // these functions are explained below + + //Script 6 + textManager.writeScript(5, 4, 0); + textManager.writeScript(9, 10, 0); + Robot.waitContinue(); + delay(500); + Robot.clearScreen(); + + //Script 7 + textManager.writeScript(6, 4, 0); + textManager.writeScript(9, 10, 0); + Robot.waitContinue(); + delay(500); + Robot.clearScreen(); + + //Script 8 + // this function enables sound and images at once + textManager.showPicture("init2.bmp", 0, 0); + + textManager.writeScript(7, 2, 0); + textManager.writeScript(9, 7, 0); + Robot.waitContinue(); + delay(500); + Robot.clearScreen(); + + //Script 9 + textManager.showPicture("init3.bmp", 0, 0); + textManager.writeScript(8, 2, 0); + textManager.writeScript(9, 7, 0); + Robot.waitContinue(); + delay(500); + Robot.clearScreen(); + + //Script 11 + textManager.writeScript(10, 4, 0); + textManager.writeScript(9, 10, 0); + Robot.waitContinue(); + delay(500); + Robot.clearScreen(); + + //Input screen + textManager.writeScript(0, 1, 1); + textManager.input(3, 1, USERNAME); + + textManager.writeScript(1, 5, 1); + textManager.input(7, 1, ROBOTNAME); + + delay(1000); + Robot.clearScreen(); + + //last screen + textManager.showPicture("init4.bmp", 0, 0); + textManager.writeText(1, 2, "Hello"); + Robot.userNameRead(buffer); + textManager.writeText(3, 2, buffer); + + textManager.writeScript(4,10,0); + + Robot.waitContinue(BUTTON_LEFT); + Robot.waitContinue(BUTTON_RIGHT); + textManager.showPicture("kt1.bmp", 0, 0); +} + +void loop(){ + // do nothing here +} + + +/** +textManager mostly contains helper functions for +R06_Wheel_Calibration and R01_Hello_User. + +The ones used in this example: + textManager.setMargin(margin_left, margin_top): + Configure the left and top margin for text + display. The margins will be used for + textManager.writeText(). + Parameters: + margin_left, margin_top: the margin values + from the top and left side of the screen. + Returns: + none + + textManager.writeScript(script_number,line,column): + Display a script of Hello User example. + Parameters: + script_number: an int value representing the + script to be displayed. + line, column: in which line,column is the script + displayed. Same as writeText(). + Returns: + none + + textManager.input(line,column,codename): + Print an input indicator(">") in the line and column, + dispaly and receive input from a virtual keyboard, + and save the value into EEPROM represented by codename + Parameters: + line,column: int values represents where the input + starts. Same as wirteText(). + codename: either USERNAME,ROBOTNAME,CITYNAME or + COUNTRYNAME. You can call Robot.userNameRead(), + robotNameRead(),cityNameRead() or countryNameRead() + to access the values later. + Returns: + none; + + textManager.writeText(line,column,text): + Display text on the specific line and column. + It's different from Robot.text() as the later + uses pixels for positioning the text. + Parameters: + line:in which line is the text displayed. Each line + is 10px high. + column:in which column is the text displayed. Each + column is 8px wide. + text:a char array(string) of the text to be displayed. + Returns: + none + + textManager.showPicture(filename, x, y): + It has the same functionality as Robot.drawPicture(), + while fixing the conflict between drawPicture() and + sound playing. Using Robot.drawPicture(), it'll have + glitches when playing sound at the same time. Using + showPicture(), it'll stop sound when displaying + picture, so preventing the problem. + Parameters: + filename:string, name of the bmp file in sd + x,y: int values, position of the picture + Returns: + none + +*/ diff --git a/libraries/Robot_Control/examples/learn/AllIOPorts/AllIOPorts.ino b/libraries/Robot_Control/examples/learn/AllIOPorts/AllIOPorts.ino new file mode 100644 index 00000000000..31ac42df723 --- /dev/null +++ b/libraries/Robot_Control/examples/learn/AllIOPorts/AllIOPorts.ino @@ -0,0 +1,151 @@ +/* + All IO Ports + + This example goes through all the IO ports on your robot and + reads/writes from/to them. Uncomment the different lines inside + the loop to test the different possibilities. + + The M inputs on the Control Board are multiplexed and therefore + it is not recommended to use them as outputs. The D pins on the + Control Board as well as the D pins on the Motor Board go directly + to the microcontroller and therefore can be used both as inputs + and outputs. + + Circuit: + * Arduino Robot + + created 1 May 2013 + by X. Yang + modified 12 May 2013 + by D. Cuartielles + + This example is in the public domain + */ + +#include +#include +#include + +// use arrays to store the names of the pins to be read +uint8_t arr[] = { M0, M1, M2, M3, M4, M5, M6, M7 }; +uint8_t arr2[] = { D0, D1, D2, D3, D4, D5 }; +uint8_t arr3[] = { D7, D8, D9, D10 }; + +void setup(){ + // initialize the robot + Robot.begin(); + + // open the serial port to send the information of what you are reading + Serial.begin(9600); +} + +void loop(){ + // read all the D inputs at the Motor Board as analog + //analogReadB_Ds(); + + // read all the D inputs at the Motor Board as digital + //digitalReadB_Ds(); + + // read all the M inputs at the Control Board as analog + //analogReadMs(); + + // read all the M inputs at the Control Board as digital + //digitalReadMs(); + + // read all the D inputs at the Control Board as analog + analogReadT_Ds(); + + // read all the D inputs at the Control Board as digital + //digitalReadT_Ds(); + + // write all the D outputs at the Motor Board as digital + //digitalWriteB_Ds(); + + // write all the D outputs at the Control Board as digital + //digitalWriteT_Ds(); + delay(40); +} + +// read all M inputs on the Control Board as analog inputs +void analogReadMs() { + for(int i=0;i<8;i++) { + Serial.print(Robot.analogRead(arr[i])); + Serial.print(","); + } + Serial.println(""); +} + +// read all M inputs on the Control Board as digital inputs +void digitalReadMs() { + for(int i=0;i<8;i++) { + Serial.print(Robot.digitalRead(arr[i])); + Serial.print(","); + } + Serial.println(""); +} + +// read all D inputs on the Control Board as analog inputs +void analogReadT_Ds() { + for(int i=0; i<6; i++) { + Serial.print(Robot.analogRead(arr2[i])); + Serial.print(","); + } + Serial.println(""); +} + +// read all D inputs on the Control Board as digital inputs +void digitalReadT_Ds() { + for(int i=0; i<6; i++) { + Serial.print(Robot.digitalRead(arr2[i])); + Serial.print(","); + } + Serial.println(""); +} + +// write all D outputs on the Control Board as digital outputs +void digitalWriteT_Ds() { + // turn all the pins on + for(int i=0; i<6; i++) { + Robot.digitalWrite(arr2[i], HIGH); + } + delay(500); + + // turn all the pins off + for(int i=0; i<6; i++){ + Robot.digitalWrite(arr2[i], LOW); + } + delay(500); +} + +// write all D outputs on the Motor Board as digital outputs +void digitalWriteB_Ds() { + // turn all the pins on + for(int i=0; i<4; i++) { + Robot.digitalWrite(arr3[i], HIGH); + } + delay(500); + + // turn all the pins off + for(int i=0; i<4; i++) { + Robot.digitalWrite(arr3[i], LOW); + } + delay(500); +} + +// read all D inputs on the Motor Board as analog inputs +void analogReadB_Ds() { + for(int i=0; i<4; i++) { + Serial.print(Robot.analogRead(arr3[i])); + Serial.print(","); + } + Serial.println(""); +} + +// read all D inputs on the Motor Board as digital inputs +void digitalReadB_Ds() { + for(int i=0; i<4; i++) { + Serial.print(Robot.digitalRead(arr3[i])); + Serial.print(","); + } + Serial.println(""); +} diff --git a/libraries/Robot_Control/examples/learn/Beep/Beep.ino b/libraries/Robot_Control/examples/learn/Beep/Beep.ino new file mode 100644 index 00000000000..77dec824417 --- /dev/null +++ b/libraries/Robot_Control/examples/learn/Beep/Beep.ino @@ -0,0 +1,41 @@ +/* + Beep + + Test different pre-configured beeps on + the robot's speaker. + + Possible beeps are: + - BEEP_SIMPLE + - BEEP_DOUBLE + - BEEP_LONG + + Circuit: + * Arduino Robot + + created 1 May 2013 + by X. Yang + modified 12 May 2013 + by D. Cuartielles + + This example is in the public domain + */ + +#include +#include +#include + +void setup() { + // initialize the robot + Robot.begin(); + + // initialize the sound speaker + Robot.beginSpeaker(); +} +void loop() { + Robot.beep(BEEP_SIMPLE); + delay(1000); + Robot.beep(BEEP_DOUBLE); + delay(1000); + Robot.beep(BEEP_LONG); + delay(1000); +} diff --git a/libraries/Robot_Control/examples/learn/CleanEEPROM/CleanEEPROM.ino b/libraries/Robot_Control/examples/learn/CleanEEPROM/CleanEEPROM.ino new file mode 100644 index 00000000000..2c418bb0f3e --- /dev/null +++ b/libraries/Robot_Control/examples/learn/CleanEEPROM/CleanEEPROM.ino @@ -0,0 +1,43 @@ +/* + Clean EEPROM + + This example erases the user information stored on the + external EEPROM memory chip on your robot. + + BEWARE, this will erase the following information: + - your name + - your robots name given by you + - your city and country if you configured them via software + + EEPROMs shouldn't be rewritten too often, therefore the + code runs only during setup and not inside loop. + + Circuit: + * Arduino Robot + + created 1 May 2013 + by X. Yang + modified 12 May 2013 + by D. Cuartielles + + This example is in the public domain + */ + +#include +#include +#include + +void setup(){ + // initialize the robot + Robot.begin(); + + // write empty strings for the different fields + Robot.userNameWrite(""); + Robot.robotNameWrite(""); + Robot.cityNameWrite(""); + Robot.countryNameWrite(""); +} + +void loop(){ + // do nothing +} diff --git a/libraries/Robot_Control/examples/learn/Compass/Compass.ino b/libraries/Robot_Control/examples/learn/Compass/Compass.ino new file mode 100644 index 00000000000..50e075be8a8 --- /dev/null +++ b/libraries/Robot_Control/examples/learn/Compass/Compass.ino @@ -0,0 +1,43 @@ +/* + Compass + + Try the compass both on the robot's TFT + and through the serial port. + + Circuit: + * Arduino Robot + + created 1 May 2013 + by X. Yang + modified 12 May 2013 + by D. Cuartielles + + This example is in the public domain + */ + +#include +#include +#include + +void setup() { + // initialize the robot + Robot.begin(); + + // initialize the robot's screen + Robot.beginTFT(); + + // initialize the serial port + Serial.begin(9600); +} + +void loop() { + // read the compass + int compass = Robot.compassRead(); + + // print out the sensor's value + Serial.println(compass); + + // show the value on the robot's screen + Robot.drawCompass(compass); +} + diff --git a/libraries/Robot_Control/examples/learn/IRArray/IRArray.ino b/libraries/Robot_Control/examples/learn/IRArray/IRArray.ino new file mode 100644 index 00000000000..207e5257a7f --- /dev/null +++ b/libraries/Robot_Control/examples/learn/IRArray/IRArray.ino @@ -0,0 +1,46 @@ +/* + IR array + + Read the analog value of the IR sensors at the + bottom of the robot. The also-called line following + sensors are a series of pairs of IR sender/receiver + used to detect how dark it is underneath the robot. + + The information coming from the sensor array is stored + into the Robot.IRarray[] and updated using the Robot.updateIR() + method. + + Circuit: + * Arduino Robot + + created 1 May 2013 + by X. Yang + modified 12 May 2013 + by D. Cuartielles + + This example is in the public domain + */ + +#include +#include +#include + +void setup(){ + // initialize the robot + Robot.begin(); + + // initialize the serial port + Serial.begin(9600); +} + +void loop(){ + // store the sensor information into the array + Robot.updateIR(); + + // iterate the array and print the data to the Serial port + for(int i=0; i<5; i++){ + Serial.print(Robot.IRarray[i]); + Serial.print(" "); + } + Serial.println(""); +} diff --git a/libraries/Robot_Control/examples/learn/LCDDebugPrint/LCDDebugPrint.ino b/libraries/Robot_Control/examples/learn/LCDDebugPrint/LCDDebugPrint.ino new file mode 100644 index 00000000000..c4d17c8bd72 --- /dev/null +++ b/libraries/Robot_Control/examples/learn/LCDDebugPrint/LCDDebugPrint.ino @@ -0,0 +1,39 @@ +/* + LCD Debug Print + + Use the Robot's library function debugPrint() to + quickly send a sensor reading to the robot's creen. + + Circuit: + * Arduino Robot + + created 1 May 2013 + by X. Yang + modified 12 May 2013 + by D. Cuartielles + + This example is in the public domain + */ + +#include +#include +#include + +int value; + +void setup() { + // initialize the robot + Robot.begin(); + + // initialize the screen + Robot.beginTFT(); +} +void loop(){ + // read a value + value = analogRead(A4); + + // send the value to the screen + Robot.debugPrint(value); + + delay(40); +} diff --git a/libraries/Robot_Control/examples/learn/LCDPrint/LCDPrint.ino b/libraries/Robot_Control/examples/learn/LCDPrint/LCDPrint.ino new file mode 100644 index 00000000000..1d87e737d76 --- /dev/null +++ b/libraries/Robot_Control/examples/learn/LCDPrint/LCDPrint.ino @@ -0,0 +1,46 @@ +/* + LCD Print + + Print the reading from a sensor to the screen. + + Circuit: + * Arduino Robot + + created 1 May 2013 + by X. Yang + modified 12 May 2013 + by D. Cuartielles + + This example is in the public domain + */ + +#include +#include +#include + +int value; + +void setup() { + // initialize the robot + Robot.begin(); + + // initialize the robot's screen + Robot.beginTFT(); +} + +void loop() { + // read a analog port + value=Robot.analogRead(TK4); + + // write the sensor value on the screen + Robot.stroke(0, 255, 0); + Robot.textSize(1); + Robot.text(value, 0, 0); + + delay(500); + + // erase the previous text on the screen + Robot.stroke(255, 255, 255); + Robot.textSize(1); + Robot.text(value, 0, 0); +} diff --git a/libraries/Robot_Control/examples/learn/LCDWriteText/LCDWriteText.ino b/libraries/Robot_Control/examples/learn/LCDWriteText/LCDWriteText.ino new file mode 100644 index 00000000000..dce0d71d24e --- /dev/null +++ b/libraries/Robot_Control/examples/learn/LCDWriteText/LCDWriteText.ino @@ -0,0 +1,43 @@ +/* + LCD Write Text + + Use the Robot's library function text() to + print out text to the robot's screen. Take + into account that you need to erase the + information before continuing writing. + + Circuit: + * Arduino Robot + + created 1 May 2013 + by X. Yang + modified 12 May 2013 + by D. Cuartielles + + This example is in the public domain + */ + +#include +#include +#include + +void setup() { + // initialize the robot + Robot.begin(); + + // initialize the screen + Robot.beginTFT(); +} +void loop() { + Robot.stroke(0, 0, 0); // choose the color black + Robot.text("Hello World", 0, 0); // print the text + delay(2000); + Robot.stroke(255, 255, 255); // choose the color white + Robot.text("Hello World", 0, 0); // writing text in the same color as the BG erases the text! + + Robot.stroke(0, 0, 0); // choose the color black + Robot.text("I am a robot", 0, 0); // print the text + delay(3000); + Robot.stroke(255, 255, 255); // choose the color black + Robot.text("I am a robot", 0, 0); // print the text +} diff --git a/libraries/Robot_Control/examples/learn/LineFollowWithPause/LineFollowWithPause.ino b/libraries/Robot_Control/examples/learn/LineFollowWithPause/LineFollowWithPause.ino new file mode 100644 index 00000000000..d03dbc1ba5c --- /dev/null +++ b/libraries/Robot_Control/examples/learn/LineFollowWithPause/LineFollowWithPause.ino @@ -0,0 +1,51 @@ +/* + Line Following with Pause + + As the robot has two processors, one to command the motors and one to + take care of the screen and user input, it is possible to write + programs that put one part of the robot to do something and get the + other half to control it. + + This example shows how the Control Board assigns the Motor one to + follow a line, but asks it to stop every 3 seconds. + + Circuit: + * Arduino Robot + + created 1 May 2013 + by X. Yang + modified 12 May 2013 + by D. Cuartielles + + This example is in the public domain + */ + +#include +#include +#include + +void setup() { + // initialize the robot + Robot.begin(); + + // initialize the screen + Robot.beginTFT(); + + // get some time to place the robot on the ground + delay(3000); + + // set the robot in line following mode + Robot.setMode(MODE_LINE_FOLLOW); +} + +void loop() { + // tell the robot to take a break and stop + Robot.pauseMode(true); + Robot.debugPrint('p'); + delay(3000); + + // tell the robot to move on + Robot.pauseMode(false); + Robot.debugPrint('>'); + delay(3000); +} diff --git a/libraries/Robot_Control/examples/learn/Melody/Melody.ino b/libraries/Robot_Control/examples/learn/Melody/Melody.ino new file mode 100644 index 00000000000..a7bf5a256cd --- /dev/null +++ b/libraries/Robot_Control/examples/learn/Melody/Melody.ino @@ -0,0 +1,64 @@ +/* + Melody + + Plays a melody stored in a string. + + The notes and durations are encoded as follows: + + NOTES: + c play "C" + C play "#C" + d play "D" + D play "#D" + e play "E" + f play "F" + F play "#F" + g play "G" + G play "#G" + a play "A" + A play "#A" + b play "B" + - silence + + DURATIONS: + 1 Set as full note + 2 Set as half note + 4 Set as quarter note + 8 Set as eigth note + + SPECIAL NOTATION: + . Make the previous note 3/4 the length + + Circuit: + * Arduino Robot + + created 1 May 2013 + by X. Yang + modified 12 May 2013 + by D. Cuartielles + + This example is in the public domain + + This code uses the Squawk sound library designed by STG. For + more information about it check: http://github.com/stg/squawk + */ + +#include +#include +#include + +void setup() { + // initialize the robot + Robot.begin(); + + // initialize the sound library + Robot.beginSpeaker(); +} + +void loop() { + // array containing the melody + char aTinyMelody[] = "8eF-FFga4b.a.g.F.8beee-d2e.1-"; + + // play the melody + Robot.playMelody(aTinyMelody); +} diff --git a/libraries/Robot_Control/examples/learn/MotorTest/MotorTest.ino b/libraries/Robot_Control/examples/learn/MotorTest/MotorTest.ino new file mode 100644 index 00000000000..5a9affebdeb --- /dev/null +++ b/libraries/Robot_Control/examples/learn/MotorTest/MotorTest.ino @@ -0,0 +1,43 @@ +/* + Motor Test + + Just see if the robot can move and turn. + + Circuit: + * Arduino Robot + + created 1 May 2013 + by X. Yang + modified 12 May 2013 + by D. Cuartielles + + This example is in the public domain + */ + +#include +#include +#include + +void setup() { + // initialize the robot + Robot.begin(); +} + +void loop() { + Robot.motorsWrite(255,255); // move forward + delay(2000); + Robot.motorsStop(); // fast stop + delay(1000); + Robot.motorsWrite(-255,-255); // backward + delay(1000); + Robot.motorsWrite(0,0); // slow stop + delay(1000); + Robot.motorsWrite(-255,255); // turn left + delay(2000); + Robot.motorsStop(); // fast stop + delay(1000); + Robot.motorsWrite(255,-255); // turn right + delay(2000); + Robot.motorsStop(); // fast stop + delay(1000); +} diff --git a/libraries/Robot_Control/examples/learn/SpeedByPotentiometer/SpeedByPotentiometer.ino b/libraries/Robot_Control/examples/learn/SpeedByPotentiometer/SpeedByPotentiometer.ino new file mode 100644 index 00000000000..9f15f8e402b --- /dev/null +++ b/libraries/Robot_Control/examples/learn/SpeedByPotentiometer/SpeedByPotentiometer.ino @@ -0,0 +1,41 @@ +/* + Speed by Potentiometer + + Control the robot's speed using the on-board + potentiometer. The speed will be printed on + the TFT screen. + + Circuit: + * Arduino Robot + + created 1 May 2013 + by X. Yang + modified 12 May 2013 + by D. Cuartielles + + This example is in the public domain + */ + +#include +#include +#include + +void setup() { + // initialize the robot + Robot.begin(); + + // initialize the screen + Robot.beginTFT(); +} + +void loop() { + // read the value of the potentiometer + int val=map(Robot.knobRead(), 0, 1023, -255, 255); + + // print the value to the TFT screen + Robot.debugPrint(val); + + // set the same speed on both of the robot's wheels + Robot.motorsWrite(val,val); + delay(10); +} diff --git a/libraries/Robot_Control/examples/learn/TurnTest/TurnTest.ino b/libraries/Robot_Control/examples/learn/TurnTest/TurnTest.ino new file mode 100644 index 00000000000..4f8d8545449 --- /dev/null +++ b/libraries/Robot_Control/examples/learn/TurnTest/TurnTest.ino @@ -0,0 +1,34 @@ +/* + Turn Test + + Check if the robot turns a certain amount of degrees. + + Circuit: + * Arduino Robot + + created 1 May 2013 + by X. Yang + modified 12 May 2013 + by D. Cuartielles + + This example is in the public domain + */ + +#include +#include +#include + +void setup() { + // initialize the robot + Robot.begin(); +} + +void loop(){ + Robot.turn(50); //turn 50 degrees to the right + Robot.motorsStop(); + delay(1000); + + Robot.turn(-100); //turn 100 degrees to the left + Robot.motorsStop(); + delay(1000); +} diff --git a/libraries/Robot_Control/examples/learn/TurnTest/TurnTest.ino.orig b/libraries/Robot_Control/examples/learn/TurnTest/TurnTest.ino.orig new file mode 100644 index 00000000000..4e3624ff9d8 --- /dev/null +++ b/libraries/Robot_Control/examples/learn/TurnTest/TurnTest.ino.orig @@ -0,0 +1,37 @@ +/* + Turn Test + + Check if the robot turns a certain amount of degrees. + + Circuit: + * Arduino Robot + + created 1 May 2013 + by X. Yang + modified 12 May 2013 + by D. Cuartielles + + This example is in the public domain + */ + +#include + +void setup() { + // initialize the robot + Robot.begin(); +} + +<<<<<<< HEAD +void loop() { + Robot.turn(50); //turn 50 degrees to the right +======= +void loop(){ + Robot.turn(50);//turn 50 degrees to the right + Robot.motorsStop(); +>>>>>>> f062f704463222e83390b4a954e211f0f7e6e66f + delay(1000); + + Robot.turn(-100);//turn 100 degrees to the left + Robot.motorsStop(); + delay(1000); +} diff --git a/libraries/Robot_Control/examples/learn/keyboardTest/keyboardTest.ino b/libraries/Robot_Control/examples/learn/keyboardTest/keyboardTest.ino new file mode 100644 index 00000000000..0bca332850f --- /dev/null +++ b/libraries/Robot_Control/examples/learn/keyboardTest/keyboardTest.ino @@ -0,0 +1,40 @@ +/* + Keyboard Test + + Check how the robot's keyboard works. This example + sends the data about the key pressed through the + serial port. + + All the buttons on the Control Board are tied up to a + single analog input pin, in this way it is possible to multiplex a + whole series of buttons on one single pin. + + It is possible to recalibrate the thresholds of the buttons using + the Robot.keyboardCalibrate() function, that takes a 5 ints long + array as parameter + + Circuit: + * Arduino Robot + + created 1 May 2013 + by X. Yang + modified 12 May 2013 + by D. Cuartielles + + This example is in the public domain + */ + +#include +#include +#include + +void setup() { + // initialize the serial port + Serial.begin(9600); +} + +void loop() { + // print out the keyboard readings + Serial.println(Robot.keyboardRead()); + delay(100); +} diff --git a/libraries/Robot_Control/examples/learn/keyboardTest/keyboardTest.ino.orig b/libraries/Robot_Control/examples/learn/keyboardTest/keyboardTest.ino.orig new file mode 100644 index 00000000000..6ee6c05e1c0 --- /dev/null +++ b/libraries/Robot_Control/examples/learn/keyboardTest/keyboardTest.ino.orig @@ -0,0 +1,49 @@ +/* + Keyboard Test + + Check how the robot's keyboard works. This example + sends the data about the key pressed through the + serial port. + + All the buttons on the Control Board are tied up to a + single analog input pin, in this way it is possible to multiplex a + whole series of buttons on one single pin. + + It is possible to recalibrate the thresholds of the buttons using + the Robot.keyboardCalibrate() function, that takes a 5 ints long + array as parameter + + Circuit: + * Arduino Robot + + created 1 May 2013 + by X. Yang + modified 12 May 2013 + by D. Cuartielles + + This example is in the public domain + */ + +#include + +<<<<<<< HEAD +// it is possible to use an array to calibrate +//int vals[] = { 0, 133, 305, 481, 724 }; + +void setup() { + // initialize the serial port + Serial.begin(9600); + + // calibrate the keyboard + //Robot.keyboardCalibrate(vals);//For the new robot only. +======= +void setup(){ + Serial.begin(9600); +>>>>>>> f062f704463222e83390b4a954e211f0f7e6e66f +} + +void loop() { + // print out the keyboard readings + Serial.println(Robot.keyboardRead()); + delay(100); +} diff --git a/libraries/Robot_Control/glcdfont.c b/libraries/Robot_Control/glcdfont.c new file mode 100644 index 00000000000..abc36317ead --- /dev/null +++ b/libraries/Robot_Control/glcdfont.c @@ -0,0 +1,266 @@ +#include +#include + +#ifndef FONT5X7_H +#define FONT5X7_H + +// standard ascii 5x7 font + +static unsigned char font[] PROGMEM = { + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x3E, 0x5B, 0x4F, 0x5B, 0x3E, + 0x3E, 0x6B, 0x4F, 0x6B, 0x3E, + 0x1C, 0x3E, 0x7C, 0x3E, 0x1C, + 0x18, 0x3C, 0x7E, 0x3C, 0x18, + 0x1C, 0x57, 0x7D, 0x57, 0x1C, + 0x1C, 0x5E, 0x7F, 0x5E, 0x1C, + 0x00, 0x18, 0x3C, 0x18, 0x00, + 0xFF, 0xE7, 0xC3, 0xE7, 0xFF, + 0x00, 0x18, 0x24, 0x18, 0x00, + 0xFF, 0xE7, 0xDB, 0xE7, 0xFF, + 0x30, 0x48, 0x3A, 0x06, 0x0E, + 0x26, 0x29, 0x79, 0x29, 0x26, + 0x40, 0x7F, 0x05, 0x05, 0x07, + 0x40, 0x7F, 0x05, 0x25, 0x3F, + 0x5A, 0x3C, 0xE7, 0x3C, 0x5A, + 0x7F, 0x3E, 0x1C, 0x1C, 0x08, + 0x08, 0x1C, 0x1C, 0x3E, 0x7F, + 0x14, 0x22, 0x7F, 0x22, 0x14, + 0x5F, 0x5F, 0x00, 0x5F, 0x5F, + 0x06, 0x09, 0x7F, 0x01, 0x7F, + 0x00, 0x66, 0x89, 0x95, 0x6A, + 0x60, 0x60, 0x60, 0x60, 0x60, + 0x94, 0xA2, 0xFF, 0xA2, 0x94, + 0x08, 0x04, 0x7E, 0x04, 0x08, + 0x10, 0x20, 0x7E, 0x20, 0x10, + 0x08, 0x08, 0x2A, 0x1C, 0x08, + 0x08, 0x1C, 0x2A, 0x08, 0x08, + 0x1E, 0x10, 0x10, 0x10, 0x10, + 0x0C, 0x1E, 0x0C, 0x1E, 0x0C, + 0x30, 0x38, 0x3E, 0x38, 0x30, + 0x06, 0x0E, 0x3E, 0x0E, 0x06, + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x5F, 0x00, 0x00, + 0x00, 0x07, 0x00, 0x07, 0x00, + 0x14, 0x7F, 0x14, 0x7F, 0x14, + 0x24, 0x2A, 0x7F, 0x2A, 0x12, + 0x23, 0x13, 0x08, 0x64, 0x62, + 0x36, 0x49, 0x56, 0x20, 0x50, + 0x00, 0x08, 0x07, 0x03, 0x00, + 0x00, 0x1C, 0x22, 0x41, 0x00, + 0x00, 0x41, 0x22, 0x1C, 0x00, + 0x2A, 0x1C, 0x7F, 0x1C, 0x2A, + 0x08, 0x08, 0x3E, 0x08, 0x08, + 0x00, 0x80, 0x70, 0x30, 0x00, + 0x08, 0x08, 0x08, 0x08, 0x08, + 0x00, 0x00, 0x60, 0x60, 0x00, + 0x20, 0x10, 0x08, 0x04, 0x02, + 0x3E, 0x51, 0x49, 0x45, 0x3E, + 0x00, 0x42, 0x7F, 0x40, 0x00, + 0x72, 0x49, 0x49, 0x49, 0x46, + 0x21, 0x41, 0x49, 0x4D, 0x33, + 0x18, 0x14, 0x12, 0x7F, 0x10, + 0x27, 0x45, 0x45, 0x45, 0x39, + 0x3C, 0x4A, 0x49, 0x49, 0x31, + 0x41, 0x21, 0x11, 0x09, 0x07, + 0x36, 0x49, 0x49, 0x49, 0x36, + 0x46, 0x49, 0x49, 0x29, 0x1E, + 0x00, 0x00, 0x14, 0x00, 0x00, + 0x00, 0x40, 0x34, 0x00, 0x00, + 0x00, 0x08, 0x14, 0x22, 0x41, + 0x14, 0x14, 0x14, 0x14, 0x14, + 0x00, 0x41, 0x22, 0x14, 0x08, + 0x02, 0x01, 0x59, 0x09, 0x06, + 0x3E, 0x41, 0x5D, 0x59, 0x4E, + 0x7C, 0x12, 0x11, 0x12, 0x7C, + 0x7F, 0x49, 0x49, 0x49, 0x36, + 0x3E, 0x41, 0x41, 0x41, 0x22, + 0x7F, 0x41, 0x41, 0x41, 0x3E, + 0x7F, 0x49, 0x49, 0x49, 0x41, + 0x7F, 0x09, 0x09, 0x09, 0x01, + 0x3E, 0x41, 0x41, 0x51, 0x73, + 0x7F, 0x08, 0x08, 0x08, 0x7F, + 0x00, 0x41, 0x7F, 0x41, 0x00, + 0x20, 0x40, 0x41, 0x3F, 0x01, + 0x7F, 0x08, 0x14, 0x22, 0x41, + 0x7F, 0x40, 0x40, 0x40, 0x40, + 0x7F, 0x02, 0x1C, 0x02, 0x7F, + 0x7F, 0x04, 0x08, 0x10, 0x7F, + 0x3E, 0x41, 0x41, 0x41, 0x3E, + 0x7F, 0x09, 0x09, 0x09, 0x06, + 0x3E, 0x41, 0x51, 0x21, 0x5E, + 0x7F, 0x09, 0x19, 0x29, 0x46, + 0x26, 0x49, 0x49, 0x49, 0x32, + 0x03, 0x01, 0x7F, 0x01, 0x03, + 0x3F, 0x40, 0x40, 0x40, 0x3F, + 0x1F, 0x20, 0x40, 0x20, 0x1F, + 0x3F, 0x40, 0x38, 0x40, 0x3F, + 0x63, 0x14, 0x08, 0x14, 0x63, + 0x03, 0x04, 0x78, 0x04, 0x03, + 0x61, 0x59, 0x49, 0x4D, 0x43, + 0x00, 0x7F, 0x41, 0x41, 0x41, + 0x02, 0x04, 0x08, 0x10, 0x20, + 0x00, 0x41, 0x41, 0x41, 0x7F, + 0x04, 0x02, 0x01, 0x02, 0x04, + 0x40, 0x40, 0x40, 0x40, 0x40, + 0x00, 0x03, 0x07, 0x08, 0x00, + 0x20, 0x54, 0x54, 0x78, 0x40, + 0x7F, 0x28, 0x44, 0x44, 0x38, + 0x38, 0x44, 0x44, 0x44, 0x28, + 0x38, 0x44, 0x44, 0x28, 0x7F, + 0x38, 0x54, 0x54, 0x54, 0x18, + 0x00, 0x08, 0x7E, 0x09, 0x02, + 0x18, 0xA4, 0xA4, 0x9C, 0x78, + 0x7F, 0x08, 0x04, 0x04, 0x78, + 0x00, 0x44, 0x7D, 0x40, 0x00, + 0x20, 0x40, 0x40, 0x3D, 0x00, + 0x7F, 0x10, 0x28, 0x44, 0x00, + 0x00, 0x41, 0x7F, 0x40, 0x00, + 0x7C, 0x04, 0x78, 0x04, 0x78, + 0x7C, 0x08, 0x04, 0x04, 0x78, + 0x38, 0x44, 0x44, 0x44, 0x38, + 0xFC, 0x18, 0x24, 0x24, 0x18, + 0x18, 0x24, 0x24, 0x18, 0xFC, + 0x7C, 0x08, 0x04, 0x04, 0x08, + 0x48, 0x54, 0x54, 0x54, 0x24, + 0x04, 0x04, 0x3F, 0x44, 0x24, + 0x3C, 0x40, 0x40, 0x20, 0x7C, + 0x1C, 0x20, 0x40, 0x20, 0x1C, + 0x3C, 0x40, 0x30, 0x40, 0x3C, + 0x44, 0x28, 0x10, 0x28, 0x44, + 0x4C, 0x90, 0x90, 0x90, 0x7C, + 0x44, 0x64, 0x54, 0x4C, 0x44, + 0x00, 0x08, 0x36, 0x41, 0x00, + 0x00, 0x00, 0x77, 0x00, 0x00, + 0x00, 0x41, 0x36, 0x08, 0x00, + 0x02, 0x01, 0x02, 0x04, 0x02, + 0x3C, 0x26, 0x23, 0x26, 0x3C, + 0x1E, 0xA1, 0xA1, 0x61, 0x12, + 0x3A, 0x40, 0x40, 0x20, 0x7A, + 0x38, 0x54, 0x54, 0x55, 0x59, + 0x21, 0x55, 0x55, 0x79, 0x41, + 0x21, 0x54, 0x54, 0x78, 0x41, + 0x21, 0x55, 0x54, 0x78, 0x40, + 0x20, 0x54, 0x55, 0x79, 0x40, + 0x0C, 0x1E, 0x52, 0x72, 0x12, + 0x39, 0x55, 0x55, 0x55, 0x59, + 0x39, 0x54, 0x54, 0x54, 0x59, + 0x39, 0x55, 0x54, 0x54, 0x58, + 0x00, 0x00, 0x45, 0x7C, 0x41, + 0x00, 0x02, 0x45, 0x7D, 0x42, + 0x00, 0x01, 0x45, 0x7C, 0x40, + 0xF0, 0x29, 0x24, 0x29, 0xF0, + 0xF0, 0x28, 0x25, 0x28, 0xF0, + 0x7C, 0x54, 0x55, 0x45, 0x00, + 0x20, 0x54, 0x54, 0x7C, 0x54, + 0x7C, 0x0A, 0x09, 0x7F, 0x49, + 0x32, 0x49, 0x49, 0x49, 0x32, + 0x32, 0x48, 0x48, 0x48, 0x32, + 0x32, 0x4A, 0x48, 0x48, 0x30, + 0x3A, 0x41, 0x41, 0x21, 0x7A, + 0x3A, 0x42, 0x40, 0x20, 0x78, + 0x00, 0x9D, 0xA0, 0xA0, 0x7D, + 0x39, 0x44, 0x44, 0x44, 0x39, + 0x3D, 0x40, 0x40, 0x40, 0x3D, + 0x3C, 0x24, 0xFF, 0x24, 0x24, + 0x48, 0x7E, 0x49, 0x43, 0x66, + 0x2B, 0x2F, 0xFC, 0x2F, 0x2B, + 0xFF, 0x09, 0x29, 0xF6, 0x20, + 0xC0, 0x88, 0x7E, 0x09, 0x03, + 0x20, 0x54, 0x54, 0x79, 0x41, + 0x00, 0x00, 0x44, 0x7D, 0x41, + 0x30, 0x48, 0x48, 0x4A, 0x32, + 0x38, 0x40, 0x40, 0x22, 0x7A, + 0x00, 0x7A, 0x0A, 0x0A, 0x72, + 0x7D, 0x0D, 0x19, 0x31, 0x7D, + 0x26, 0x29, 0x29, 0x2F, 0x28, + 0x26, 0x29, 0x29, 0x29, 0x26, + 0x30, 0x48, 0x4D, 0x40, 0x20, + 0x38, 0x08, 0x08, 0x08, 0x08, + 0x08, 0x08, 0x08, 0x08, 0x38, + 0x2F, 0x10, 0xC8, 0xAC, 0xBA, + 0x2F, 0x10, 0x28, 0x34, 0xFA, + 0x00, 0x00, 0x7B, 0x00, 0x00, + 0x08, 0x14, 0x2A, 0x14, 0x22, + 0x22, 0x14, 0x2A, 0x14, 0x08, + 0xAA, 0x00, 0x55, 0x00, 0xAA, + 0xAA, 0x55, 0xAA, 0x55, 0xAA, + 0x00, 0x00, 0x00, 0xFF, 0x00, + 0x10, 0x10, 0x10, 0xFF, 0x00, + 0x14, 0x14, 0x14, 0xFF, 0x00, + 0x10, 0x10, 0xFF, 0x00, 0xFF, + 0x10, 0x10, 0xF0, 0x10, 0xF0, + 0x14, 0x14, 0x14, 0xFC, 0x00, + 0x14, 0x14, 0xF7, 0x00, 0xFF, + 0x00, 0x00, 0xFF, 0x00, 0xFF, + 0x14, 0x14, 0xF4, 0x04, 0xFC, + 0x14, 0x14, 0x17, 0x10, 0x1F, + 0x10, 0x10, 0x1F, 0x10, 0x1F, + 0x14, 0x14, 0x14, 0x1F, 0x00, + 0x10, 0x10, 0x10, 0xF0, 0x00, + 0x00, 0x00, 0x00, 0x1F, 0x10, + 0x10, 0x10, 0x10, 0x1F, 0x10, + 0x10, 0x10, 0x10, 0xF0, 0x10, + 0x00, 0x00, 0x00, 0xFF, 0x10, + 0x10, 0x10, 0x10, 0x10, 0x10, + 0x10, 0x10, 0x10, 0xFF, 0x10, + 0x00, 0x00, 0x00, 0xFF, 0x14, + 0x00, 0x00, 0xFF, 0x00, 0xFF, + 0x00, 0x00, 0x1F, 0x10, 0x17, + 0x00, 0x00, 0xFC, 0x04, 0xF4, + 0x14, 0x14, 0x17, 0x10, 0x17, + 0x14, 0x14, 0xF4, 0x04, 0xF4, + 0x00, 0x00, 0xFF, 0x00, 0xF7, + 0x14, 0x14, 0x14, 0x14, 0x14, + 0x14, 0x14, 0xF7, 0x00, 0xF7, + 0x14, 0x14, 0x14, 0x17, 0x14, + 0x10, 0x10, 0x1F, 0x10, 0x1F, + 0x14, 0x14, 0x14, 0xF4, 0x14, + 0x10, 0x10, 0xF0, 0x10, 0xF0, + 0x00, 0x00, 0x1F, 0x10, 0x1F, + 0x00, 0x00, 0x00, 0x1F, 0x14, + 0x00, 0x00, 0x00, 0xFC, 0x14, + 0x00, 0x00, 0xF0, 0x10, 0xF0, + 0x10, 0x10, 0xFF, 0x10, 0xFF, + 0x14, 0x14, 0x14, 0xFF, 0x14, + 0x10, 0x10, 0x10, 0x1F, 0x00, + 0x00, 0x00, 0x00, 0xF0, 0x10, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, + 0xFF, 0xFF, 0xFF, 0x00, 0x00, + 0x00, 0x00, 0x00, 0xFF, 0xFF, + 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, + 0x38, 0x44, 0x44, 0x38, 0x44, + 0x7C, 0x2A, 0x2A, 0x3E, 0x14, + 0x7E, 0x02, 0x02, 0x06, 0x06, + 0x02, 0x7E, 0x02, 0x7E, 0x02, + 0x63, 0x55, 0x49, 0x41, 0x63, + 0x38, 0x44, 0x44, 0x3C, 0x04, + 0x40, 0x7E, 0x20, 0x1E, 0x20, + 0x06, 0x02, 0x7E, 0x02, 0x02, + 0x99, 0xA5, 0xE7, 0xA5, 0x99, + 0x1C, 0x2A, 0x49, 0x2A, 0x1C, + 0x4C, 0x72, 0x01, 0x72, 0x4C, + 0x30, 0x4A, 0x4D, 0x4D, 0x30, + 0x30, 0x48, 0x78, 0x48, 0x30, + 0xBC, 0x62, 0x5A, 0x46, 0x3D, + 0x3E, 0x49, 0x49, 0x49, 0x00, + 0x7E, 0x01, 0x01, 0x01, 0x7E, + 0x2A, 0x2A, 0x2A, 0x2A, 0x2A, + 0x44, 0x44, 0x5F, 0x44, 0x44, + 0x40, 0x51, 0x4A, 0x44, 0x40, + 0x40, 0x44, 0x4A, 0x51, 0x40, + 0x00, 0x00, 0xFF, 0x01, 0x03, + 0xE0, 0x80, 0xFF, 0x00, 0x00, + 0x08, 0x08, 0x6B, 0x6B, 0x08, + 0x36, 0x12, 0x36, 0x24, 0x36, + 0x06, 0x0F, 0x09, 0x0F, 0x06, + 0x00, 0x00, 0x18, 0x18, 0x00, + 0x00, 0x00, 0x10, 0x10, 0x00, + 0x30, 0x40, 0xFF, 0x01, 0x01, + 0x00, 0x1F, 0x01, 0x01, 0x1E, + 0x00, 0x19, 0x1D, 0x17, 0x12, + 0x00, 0x3C, 0x3C, 0x3C, 0x3C, + 0x00, 0x00, 0x00, 0x00, 0x00, +}; +#endif diff --git a/libraries/Robot_Control/helper.cpp b/libraries/Robot_Control/helper.cpp new file mode 100644 index 00000000000..a7a956aa502 --- /dev/null +++ b/libraries/Robot_Control/helper.cpp @@ -0,0 +1,45 @@ +#include "ArduinoRobot.h" + +void RobotControl::drawBase(){ + Arduino_LCD::drawCircle(64,80,50,foreGround); + Arduino_LCD::drawLine(64,30,64,20,foreGround); +} +void RobotControl::drawDire(int16_t dire){ + static uint8_t x_old; + static uint8_t y_old; + static uint8_t x_t_old; + static uint8_t y_t_old; + + uint8_t x=60*sin(dire/360.0*6.28)+64; + uint8_t x_t=40*sin(dire/360.0*6.28)+64; + uint8_t y=60*cos(dire/360.0*6.28)+80; + uint8_t y_t=40*cos(dire/360.0*6.28)+80; + + Arduino_LCD::drawLine(x_t_old,y_t_old,x_old,y_old,backGround); + Arduino_LCD::drawLine(x_t,y_t,x,y,RED); + + x_old=x; + y_old=y; + x_t_old=x_t; + y_t_old=y_t; +} + +void RobotControl::drawCompass(uint16_t value){ + drawBase(); + drawDire(value); + debugPrint(value,57,76); +} + +//display logos +void RobotControl::displayLogos(){ + _drawBMP("lg0.bmp",0,0); + delay(2000); + _drawBMP("lg1.bmp",0,0); + delay(2000); + clearScreen(); +} + +//wait for a button to be pressed +void RobotControl::waitContinue(uint8_t key){ + while(!(Robot.keyboardRead()==key)); +} diff --git a/libraries/Robot_Control/information.cpp b/libraries/Robot_Control/information.cpp new file mode 100644 index 00000000000..c36e9cedf8a --- /dev/null +++ b/libraries/Robot_Control/information.cpp @@ -0,0 +1,41 @@ +/*#include +//0 - 319: pic array, + +//320 - 337 username, +#define ADDRESS_USERNAME 320 +//338 - 355 robotname, +#define ADDRESS_ROBOTNAME 338 +//356 - 373 cityname, +#define ADDRESS_CITYNAME 356 + //374- 391 countryname, +#define ADDRESS_COUNTRYNAME 374 +//508-511 robot info +#define ADDRESS_ROBOTINFO 508 + + +void RobotControl::getMyName(char* container){ + EEPROM_I2C::readBuffer(ADDRESS_USERNAME,(uint8_t*)container,18); +} +void RobotControl::getRobotName(char* container){ + EEPROM_I2C::readBuffer(ADDRESS_ROBOTNAME,(uint8_t*)container,18); +} +void RobotControl::getMyCity(char* container){ + EEPROM_I2C::readBuffer(ADDRESS_CITYNAME,(uint8_t*)container,18); +} +void RobotControl::getMyCountry(char* container){ + EEPROM_I2C::readBuffer(ADDRESS_COUNTRYNAME,(uint8_t*)container,18); +} + +void RobotControl::setMyName(char* text){ + EEPROM_I2C::writePage(ADDRESS_USERNAME,(uint8_t*)text,18); +} +void RobotControl::setRobotName(char* text){ + EEPROM_I2C::writePage(ADDRESS_ROBOTNAME,(uint8_t*)text,18); +} +void RobotControl::setMyCity(char* text){ + EEPROM_I2C::writePage(ADDRESS_CITYNAME,(uint8_t*)text,18); +} +void RobotControl::setMyCountry(char* text){ + EEPROM_I2C::writePage(ADDRESS_COUNTRYNAME,(uint8_t*)text,18); +} +*/ \ No newline at end of file diff --git a/libraries/Robot_Control/keyboard.cpp b/libraries/Robot_Control/keyboard.cpp new file mode 100644 index 00000000000..7e647bb3208 --- /dev/null +++ b/libraries/Robot_Control/keyboard.cpp @@ -0,0 +1,65 @@ +#include "ArduinoRobot.h" + +#if ARDUINO >= 100 +#include "Arduino.h" +#else +#include "WProgram.h" +#endif +int pul_min[]={0,133,319,494,732}; +int pul_max[]={10,153,339,514,752}; +/*int pul_min[]={0,123,295,471,714}; +int pul_max[]={0,143,315,491,734};*/ +/* +int pul_min[]={0,133,319,494,732}; +int pul_max[]={10,153,339,514,752}; +*/ +void sort(int* v); + +void RobotControl::keyboardCalibrate(int *vals){ + for(int i=0;i<5;i++){ + pul_min[i]=vals[i]-10; + pul_max[i]=vals[i]+10; + } +} +int8_t RobotControl::keyboardRead(void) +{ + + int lectura_pul; + int8_t conta_pul=0; + static int anterior=0; + + lectura_pul = this->averageAnalogInput(KEY); + + while ((conta_pul < NUMBER_BUTTONS) && !(lectura_pul >= pul_min[conta_pul] && lectura_pul <= pul_max[conta_pul])) + conta_pul++; + + if (conta_pul >= NUMBER_BUTTONS) + conta_pul = -1; + else + delay(100); + + return conta_pul; +} + +int RobotControl::averageAnalogInput(int pinNum) +{ + int vals[5]; + for(int i=0;i<5;i++){ + for(int j=i;j<5;j++){ + vals[j]=::analogRead(pinNum); + } + sort(vals); + } + return vals[0]; +} +void sort(int* v){ + int tmp; + for(int i=0;i<4;i++) + for(int j=i+1;j<5;j++) + if(v[j]foreGround=foreGround; + this->backGround=backGround; +} +void RobotControl::_enableLCD(){ + DDRB = DDRB & 0xEF; //pinMode(CS_SD,INPUT); + DDRB = DDRB | 0x20; //pinMode(CS_LCD,OUTPUT); +} +/*void RobotControl::_setErase(uint8_t posX, uint8_t posY){ + Arduino_LCD::setCursor(posX,posY); + Arduino_LCD::setTextColor(backGround); + Arduino_LCD::setTextSize(1); +} +void RobotControl::_setWrite(uint8_t posX, uint8_t posY){ + Arduino_LCD::setCursor(posX,posY); + Arduino_LCD::setTextColor(foreGround); + Arduino_LCD::setTextSize(1); +}*/ +/* +void RobotControl::text(int value, uint8_t posX, uint8_t posY, bool EW){ + if(EW) + _setWrite(posX,posY); + else + _setErase(posX,posY); + Arduino_LCD::print(value); +} +void RobotControl::text(long value, uint8_t posX, uint8_t posY, bool EW){ + if(EW) + _setWrite(posX,posY); + else + _setErase(posX,posY); + Arduino_LCD::print(value); +} +void RobotControl::text(char* value, uint8_t posX, uint8_t posY, bool EW){ + if(EW) + _setWrite(posX,posY); + else + _setErase(posX,posY); + Arduino_LCD::print(value); +} +void RobotControl::text(char value, uint8_t posX, uint8_t posY, bool EW){ + if(EW) + _setWrite(posX,posY); + else + _setErase(posX,posY); + Arduino_LCD::print(value); +} +*/ + +void RobotControl::debugPrint(long value, uint8_t x, uint8_t y){ + static long oldVal=0; + Arduino_LCD::stroke(backGround); + text(oldVal,x,y); + Arduino_LCD::stroke(foreGround); + text(value,x,y); + oldVal=value; +} + +void RobotControl::clearScreen(){ + Arduino_LCD::fillScreen(backGround); +} + +void RobotControl::drawBMP(char* filename, uint8_t x, uint8_t y){ + /*for(int j=0;j= screenWidth) || (y >= screenHeight)) return; + + // Crop area to be loaded + if((x+width-1) >= screenWidth) width = screenWidth - x; + if((y+height-1) >= screenHeight) height = screenHeight - y; + + // Set TFT address window to clipped image bounds + Arduino_LCD::setAddrWindow(x, y, x+width-1, y+height-1); + + // launch the reading command + _drawBMP_EEPROM(iconOffset, width, height); +} + +// Draw BMP from SD card through the filename +void RobotControl::_drawBMP(char* filename, uint8_t posX, uint8_t posY){ + uint8_t bmpWidth, bmpHeight; // W+H in pixels + uint8_t bmpDepth; // Bit depth (currently must be 24) + uint32_t bmpImageoffset; // Start of image data in file + uint32_t rowSize; // Not always = bmpWidth; may have padding + uint8_t sdbuffer[3*BUFFPIXEL]; // pixel buffer (R+G+B per pixel) + uint8_t buffidx = sizeof(sdbuffer); // Current position in sdbuffer + bool goodBmp = false; // Set to true on valid header parse + bool flip = true; // BMP is stored bottom-to-top + uint8_t w, h, row, col; + uint8_t r, g, b; + uint32_t pos = 0; + + // Open requested file on SD card + if ((file.open(filename,O_READ)) == NULL) { + return; + } + + // Parse BMP header + if(read16(file) == 0x4D42) { // BMP signature + read32(file);//uint32_t aux = read32(file); + (void)read32(file); // Read & ignore creator bytes + bmpImageoffset = read32(file); // Start of image data + + // Read DIB header + (void)read32(file);//aux = read32(file); + bmpWidth = read32(file); + bmpHeight = read32(file); + + if(read16(file) == 1) { // # planes -- must be '1' + bmpDepth = read16(file); // bits per pixel + if((bmpDepth == 24) && (read32(file) == 0)) { // 0 = uncompressed + goodBmp = true; // Supported BMP format -- proceed! + + // BMP rows are padded (if needed) to 4-byte boundary + rowSize = (bmpWidth * 3 + 3) & ~3; + + // If bmpHeight is negative, image is in top-down order. + // This is not canon but has been observed in the wild. + if(bmpHeight < 0) { + bmpHeight = -bmpHeight; + flip = false; + } + + // Crop area to be loaded + w = bmpWidth; + h = bmpHeight; + + // Start drawing + //_enableLCD(); + Arduino_LCD::setAddrWindow(posX, posY, posX+bmpWidth-1, posY+bmpHeight-1); + + for (row=0; row= sizeof(sdbuffer)) { // Indeed + //_enableSD(); + file.read(sdbuffer, sizeof(sdbuffer)); + buffidx = 0; // Set index to beginning + //_enableLCD(); + } + // Convert pixel from BMP to TFT format, push to display + b = sdbuffer[buffidx++]; + g = sdbuffer[buffidx++]; + r = sdbuffer[buffidx++]; + + int color = Arduino_LCD::Color565(r,g,b); + + Arduino_LCD::pushColor(color); + } // end pixel + } // end scanline + //_enableSD(); + } // end goodBmp*/ + } + } + file.close(); + //_enableLCD(); +} +uint16_t read16(Fat16& f) { + uint16_t result; + f.read(&result,sizeof(result)); + return result; +} +uint32_t read32(Fat16& f) { + uint32_t result; + f.read(&result,sizeof(result)); + return result; +} +/* +uint16_t color565(uint8_t r, uint8_t g, uint8_t b) { + return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3); +}*/ + + +void RobotControl::_drawBMP_EEPROM(uint16_t address, uint8_t width, uint8_t height){ + uint16_t u16retVal = 0; + EEPROM_I2C::_beginTransmission(address); + EEPROM_I2C::_endTransmission(); + /*Wire.beginTransmission(DEVICEADDRESS); + Wire.write( (address >> 8) & 0xFF ); + Wire.write( (address >> 0) & 0xFF ); + Wire.endTransmission();*/ + + long s = width * height ; + for(long j = 0; j < (long) s >> 4; j++) { // divided by 32, times 2 + Wire.requestFrom(DEVICEADDRESS, 32); + for(int i = 0; i < 32; i+=2) { + u16retVal = Wire.read(); + u16retVal = (u16retVal << 8) + Wire.read(); + Arduino_LCD::pushColor(u16retVal); + } + } + +} +void RobotControl::beginBMPFromEEPROM(){ + _eeprom_bmp=(EEPROM_BMP*)malloc(NUM_EEPROM_BMP*sizeof(EEPROM_BMP)); + EEPROM_I2C::_beginTransmission(0); + EEPROM_I2C::_endTransmission(); + + for(uint8_t j=0;j +#else + #define pgm_read_byte(addr) (*(const unsigned char *)(addr)) +#endif + +Adafruit_GFX::Adafruit_GFX(int16_t w, int16_t h): + WIDTH(w), HEIGHT(h) +{ + _width = WIDTH; + _height = HEIGHT; + rotation = 0; + cursor_y = cursor_x = 0; + textsize = 1; + textcolor = textbgcolor = 0xFFFF; + wrap = true; +} + +// Draw a circle outline +void Adafruit_GFX::drawCircle(int16_t x0, int16_t y0, int16_t r, + uint16_t color) { + int16_t f = 1 - r; + int16_t ddF_x = 1; + int16_t ddF_y = -2 * r; + int16_t x = 0; + int16_t y = r; + + drawPixel(x0 , y0+r, color); + drawPixel(x0 , y0-r, color); + drawPixel(x0+r, y0 , color); + drawPixel(x0-r, y0 , color); + + while (x= 0) { + y--; + ddF_y += 2; + f += ddF_y; + } + x++; + ddF_x += 2; + f += ddF_x; + + drawPixel(x0 + x, y0 + y, color); + drawPixel(x0 - x, y0 + y, color); + drawPixel(x0 + x, y0 - y, color); + drawPixel(x0 - x, y0 - y, color); + drawPixel(x0 + y, y0 + x, color); + drawPixel(x0 - y, y0 + x, color); + drawPixel(x0 + y, y0 - x, color); + drawPixel(x0 - y, y0 - x, color); + } +} + +void Adafruit_GFX::drawCircleHelper( int16_t x0, int16_t y0, + int16_t r, uint8_t cornername, uint16_t color) { + int16_t f = 1 - r; + int16_t ddF_x = 1; + int16_t ddF_y = -2 * r; + int16_t x = 0; + int16_t y = r; + + while (x= 0) { + y--; + ddF_y += 2; + f += ddF_y; + } + x++; + ddF_x += 2; + f += ddF_x; + if (cornername & 0x4) { + drawPixel(x0 + x, y0 + y, color); + drawPixel(x0 + y, y0 + x, color); + } + if (cornername & 0x2) { + drawPixel(x0 + x, y0 - y, color); + drawPixel(x0 + y, y0 - x, color); + } + if (cornername & 0x8) { + drawPixel(x0 - y, y0 + x, color); + drawPixel(x0 - x, y0 + y, color); + } + if (cornername & 0x1) { + drawPixel(x0 - y, y0 - x, color); + drawPixel(x0 - x, y0 - y, color); + } + } +} + +void Adafruit_GFX::fillCircle(int16_t x0, int16_t y0, int16_t r, + uint16_t color) { + drawFastVLine(x0, y0-r, 2*r+1, color); + fillCircleHelper(x0, y0, r, 3, 0, color); +} + +// Used to do circles and roundrects +void Adafruit_GFX::fillCircleHelper(int16_t x0, int16_t y0, int16_t r, + uint8_t cornername, int16_t delta, uint16_t color) { + + int16_t f = 1 - r; + int16_t ddF_x = 1; + int16_t ddF_y = -2 * r; + int16_t x = 0; + int16_t y = r; + + while (x= 0) { + y--; + ddF_y += 2; + f += ddF_y; + } + x++; + ddF_x += 2; + f += ddF_x; + + if (cornername & 0x1) { + drawFastVLine(x0+x, y0-y, 2*y+1+delta, color); + drawFastVLine(x0+y, y0-x, 2*x+1+delta, color); + } + if (cornername & 0x2) { + drawFastVLine(x0-x, y0-y, 2*y+1+delta, color); + drawFastVLine(x0-y, y0-x, 2*x+1+delta, color); + } + } +} + +// Bresenham's algorithm - thx wikpedia +void Adafruit_GFX::drawLine(int16_t x0, int16_t y0, + int16_t x1, int16_t y1, + uint16_t color) { + int16_t steep = abs(y1 - y0) > abs(x1 - x0); + if (steep) { + swap(x0, y0); + swap(x1, y1); + } + + if (x0 > x1) { + swap(x0, x1); + swap(y0, y1); + } + + int16_t dx, dy; + dx = x1 - x0; + dy = abs(y1 - y0); + + int16_t err = dx / 2; + int16_t ystep; + + if (y0 < y1) { + ystep = 1; + } else { + ystep = -1; + } + + for (; x0<=x1; x0++) { + if (steep) { + drawPixel(y0, x0, color); + } else { + drawPixel(x0, y0, color); + } + err -= dy; + if (err < 0) { + y0 += ystep; + err += dx; + } + } +} + +// Draw a rectangle +void Adafruit_GFX::drawRect(int16_t x, int16_t y, + int16_t w, int16_t h, + uint16_t color) { + drawFastHLine(x, y, w, color); + drawFastHLine(x, y+h-1, w, color); + drawFastVLine(x, y, h, color); + drawFastVLine(x+w-1, y, h, color); +} + +void Adafruit_GFX::drawFastVLine(int16_t x, int16_t y, + int16_t h, uint16_t color) { + // Update in subclasses if desired! + drawLine(x, y, x, y+h-1, color); +} + +void Adafruit_GFX::drawFastHLine(int16_t x, int16_t y, + int16_t w, uint16_t color) { + // Update in subclasses if desired! + drawLine(x, y, x+w-1, y, color); +} + +void Adafruit_GFX::fillRect(int16_t x, int16_t y, int16_t w, int16_t h, + uint16_t color) { + // Update in subclasses if desired! + for (int16_t i=x; i= y1 >= y0) + if (y0 > y1) { + swap(y0, y1); swap(x0, x1); + } + if (y1 > y2) { + swap(y2, y1); swap(x2, x1); + } + if (y0 > y1) { + swap(y0, y1); swap(x0, x1); + } + + if(y0 == y2) { // Handle awkward all-on-same-line case as its own thing + a = b = x0; + if(x1 < a) a = x1; + else if(x1 > b) b = x1; + if(x2 < a) a = x2; + else if(x2 > b) b = x2; + drawFastHLine(a, y0, b-a+1, color); + return; + } + + int16_t + dx01 = x1 - x0, + dy01 = y1 - y0, + dx02 = x2 - x0, + dy02 = y2 - y0, + dx12 = x2 - x1, + dy12 = y2 - y1, + sa = 0, + sb = 0; + + // For upper part of triangle, find scanline crossings for segments + // 0-1 and 0-2. If y1=y2 (flat-bottomed triangle), the scanline y1 + // is included here (and second loop will be skipped, avoiding a /0 + // error there), otherwise scanline y1 is skipped here and handled + // in the second loop...which also avoids a /0 error here if y0=y1 + // (flat-topped triangle). + if(y1 == y2) last = y1; // Include y1 scanline + else last = y1-1; // Skip it + + for(y=y0; y<=last; y++) { + a = x0 + sa / dy01; + b = x0 + sb / dy02; + sa += dx01; + sb += dx02; + /* longhand: + a = x0 + (x1 - x0) * (y - y0) / (y1 - y0); + b = x0 + (x2 - x0) * (y - y0) / (y2 - y0); + */ + if(a > b) swap(a,b); + drawFastHLine(a, y, b-a+1, color); + } + + // For lower part of triangle, find scanline crossings for segments + // 0-2 and 1-2. This loop is skipped if y1=y2. + sa = dx12 * (y - y1); + sb = dx02 * (y - y0); + for(; y<=y2; y++) { + a = x1 + sa / dy12; + b = x0 + sb / dy02; + sa += dx12; + sb += dx02; + /* longhand: + a = x1 + (x2 - x1) * (y - y1) / (y2 - y1); + b = x0 + (x2 - x0) * (y - y0) / (y2 - y0); + */ + if(a > b) swap(a,b); + drawFastHLine(a, y, b-a+1, color); + } +} + +void Adafruit_GFX::drawBitmap(int16_t x, int16_t y, + const uint8_t *bitmap, int16_t w, int16_t h, + uint16_t color) { + + int16_t i, j, byteWidth = (w + 7) / 8; + + for(j=0; j> (i & 7))) { + drawPixel(x+i, y+j, color); + } + } + } +} + +#if ARDUINO >= 100 +size_t Adafruit_GFX::write(uint8_t c) { +#else +void Adafruit_GFX::write(uint8_t c) { +#endif + if (c == '\n') { + cursor_y += textsize*8; + cursor_x = 0; + } else if (c == '\r') { + // skip em + } else { + drawChar(cursor_x, cursor_y, c, textcolor, textbgcolor, textsize); + cursor_x += textsize*6; + if (wrap && (cursor_x > (_width - textsize*6))) { + cursor_y += textsize*8; + cursor_x = 0; + } + } +#if ARDUINO >= 100 + return 1; +#endif +} + +// Draw a character +void Adafruit_GFX::drawChar(int16_t x, int16_t y, unsigned char c, + uint16_t color, uint16_t bg, uint8_t size) { + + if((x >= _width) || // Clip right + (y >= _height) || // Clip bottom + ((x + 6 * size - 1) < 0) || // Clip left + ((y + 8 * size - 1) < 0)) // Clip top + return; + + for (int8_t i=0; i<6; i++ ) { + uint8_t line; + if (i == 5) + line = 0x0; + else + line = pgm_read_byte(font+(c*5)+i); + for (int8_t j = 0; j<8; j++) { + if (line & 0x1) { + if (size == 1) // default size + drawPixel(x+i, y+j, color); + else { // big size + fillRect(x+(i*size), y+(j*size), size, size, color); + } + } else if (bg != color) { + if (size == 1) // default size + drawPixel(x+i, y+j, bg); + else { // big size + fillRect(x+i*size, y+j*size, size, size, bg); + } + } + line >>= 1; + } + } +} + +void Adafruit_GFX::setCursor(int16_t x, int16_t y) { + cursor_x = x; + cursor_y = y; +} + +void Adafruit_GFX::setTextSize(uint8_t s) { + textsize = (s > 0) ? s : 1; +} + +void Adafruit_GFX::setTextColor(uint16_t c) { + // For 'transparent' background, we'll set the bg + // to the same as fg instead of using a flag + textcolor = textbgcolor = c; +} + +void Adafruit_GFX::setTextColor(uint16_t c, uint16_t b) { + textcolor = c; + textbgcolor = b; +} + +void Adafruit_GFX::setTextWrap(boolean w) { + wrap = w; +} + +uint8_t Adafruit_GFX::getRotation(void) { + return rotation; +} + +void Adafruit_GFX::setRotation(uint8_t x) { + rotation = (x & 3); + switch(rotation) { + case 0: + case 2: + _width = WIDTH; + _height = HEIGHT; + break; + case 1: + case 3: + _width = HEIGHT; + _height = WIDTH; + break; + } +} + +// Return the size of the display (per current rotation) +int16_t Adafruit_GFX::width(void) { + return _width; +} + +int16_t Adafruit_GFX::height(void) { + return _height; +} + +void Adafruit_GFX::invertDisplay(boolean i) { + // Do nothing, must be subclassed if supported +} + +uint16_t Adafruit_GFX::newColor(uint8_t r, uint8_t g, uint8_t b) { + return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3); +} + +void Adafruit_GFX::background(uint8_t red, uint8_t green, uint8_t blue) { + background(newColor(red, green, blue)); +} + +void Adafruit_GFX::background(color c) { + fillScreen(c); +} + +void Adafruit_GFX::stroke(uint8_t red, uint8_t green, uint8_t blue) { + stroke(newColor(red, green, blue)); +} + +void Adafruit_GFX::stroke(color c) { + useStroke = true; + strokeColor = c; + setTextColor(c); +} + +void Adafruit_GFX::noStroke() { + useStroke = false; +} + +void Adafruit_GFX::noFill() { + useFill = false; +} + +void Adafruit_GFX::fill(uint8_t red, uint8_t green, uint8_t blue) { + fill(newColor(red, green, blue)); +} + +void Adafruit_GFX::fill(color c) { + useFill = true; + fillColor = c; +} + +void Adafruit_GFX::text(int value, uint8_t x, uint8_t y){ + if (!useStroke) + return; + + setTextWrap(false); + setTextColor(strokeColor); + setCursor(x, y); + print(value); +} +void Adafruit_GFX::text(long value, uint8_t x, uint8_t y){ + if (!useStroke) + return; + + setTextWrap(false); + setTextColor(strokeColor); + setCursor(x, y); + print(value); +} +void Adafruit_GFX::text(char value, uint8_t x, uint8_t y){ + if (!useStroke) + return; + + setTextWrap(false); + setTextColor(strokeColor); + setCursor(x, y); + print(value); +} + +void Adafruit_GFX::text(const char * text, int16_t x, int16_t y) { + if (!useStroke) + return; + + setTextWrap(false); + setTextColor(strokeColor); + setCursor(x, y); + print(text); +} + +void Adafruit_GFX::textWrap(const char * text, int16_t x, int16_t y) { + if (!useStroke) + return; + + setTextWrap(true); + setTextColor(strokeColor); + setCursor(x, y); + print(text); +} + + +void Adafruit_GFX::textSize(uint8_t size) { + setTextSize(size); +} + +void Adafruit_GFX::point(int16_t x, int16_t y) { + if (!useStroke) + return; + + drawPixel(x, y, strokeColor); +} + +void Adafruit_GFX::line(int16_t x1, int16_t y1, int16_t x2, int16_t y2) { + if (!useStroke) + return; + + if (x1 == x2) { + drawFastVLine(x1, y1, y2 - y1, strokeColor); + } + else if (y1 == y2) { + drawFastHLine(x1, y1, x2 - x1, strokeColor); + } + else { + drawLine(x1, y1, x2, y2, strokeColor); + } +} + +void Adafruit_GFX::rect(int16_t x, int16_t y, int16_t width, int16_t height) { + if (useFill) { + fillRect(x, y, width, height, fillColor); + } + if (useStroke) { + drawRect(x, y, width, height, strokeColor); + } +} + +void Adafruit_GFX::rect(int16_t x, int16_t y, int16_t width, int16_t height, int16_t radius) { + if (radius == 0) { + rect(x, y, width, height); + } + if (useFill) { + fillRoundRect(x, y, width, height, radius, fillColor); + } + if (useStroke) { + drawRoundRect(x, y, width, height, radius, strokeColor); + } +} + +void Adafruit_GFX::circle(int16_t x, int16_t y, int16_t r) { + if (r == 0) + return; + + if (useFill) { + fillCircle(x, y, r, fillColor); + } + if (useStroke) { + drawCircle(x, y, r, strokeColor); + } +} + +void Adafruit_GFX::triangle(int16_t x1, int16_t y1, int16_t x2, int16_t y2, int16_t x3, int16_t y3) { + if (useFill) { + fillTriangle(x1, y1, x2, y2, x3, y3, fillColor); + } + if (useStroke) { + drawTriangle(x1, y1, x2, y2, x3, y3, strokeColor); + } +} + +#define BUFFPIXEL 20 +/* +void Adafruit_GFX::image(PImage & img, uint16_t x, uint16_t y) { + int w, h, row, col; + uint8_t r, g, b; + uint32_t pos = 0; + uint8_t sdbuffer[3*BUFFPIXEL]; // pixel buffer (R+G+B per pixel) + uint8_t buffidx = sizeof(sdbuffer); // Current position in sdbuffer + + // Crop area to be loaded + w = img._bmpWidth; + h = img._bmpHeight; + if((x+w-1) >= width()) w = width() - x; + if((y+h-1) >= height()) h = height() - y; + + + // Set TFT address window to clipped image bounds + //setAddrWindow(x, y, x+w-1, y+h-1); + + + for (row=0; row= sizeof(sdbuffer)) { // Indeed + img._bmpFile.read(sdbuffer, sizeof(sdbuffer)); + buffidx = 0; // Set index to beginning + } + + // Convert pixel from BMP to TFT format, push to display + b = sdbuffer[buffidx++]; + g = sdbuffer[buffidx++]; + r = sdbuffer[buffidx++]; + //pushColor(tft.Color565(r,g,b)); + drawPixel(x + col, y + row, newColor(r, g, b)); + + } // end pixel + } // end scanline + +}*/ diff --git a/libraries/Robot_Control/utility/Adafruit_GFX.h b/libraries/Robot_Control/utility/Adafruit_GFX.h new file mode 100644 index 00000000000..5cbc9d73d49 --- /dev/null +++ b/libraries/Robot_Control/utility/Adafruit_GFX.h @@ -0,0 +1,190 @@ +/****************************************************************** + This is the core graphics library for all our displays, providing + basic graphics primitives (points, lines, circles, etc.). It needs + to be paired with a hardware-specific library for each display + device we carry (handling the lower-level functions). + + Adafruit invests time and resources providing this open + source code, please support Adafruit and open-source hardware + by purchasing products from Adafruit! + + Written by Limor Fried/Ladyada for Adafruit Industries. + BSD license, check license.txt for more information. + All text above must be included in any redistribution. + ******************************************************************/ + +#ifndef _ADAFRUIT_GFX_H +#define _ADAFRUIT_GFX_H + +#if ARDUINO >= 100 + #include "Arduino.h" + #include "Print.h" +#else + #include "WProgram.h" +#endif + +//#include "PImage.h" + +#define swap(a, b) { int16_t t = a; a = b; b = t; } + +/* TODO +enum RectMode { + CORNER, + CORNERS, + RADIUS, + CENTER +}; +*/ + +typedef uint16_t color; + +class Adafruit_GFX : public Print { + public: + + Adafruit_GFX(int16_t w, int16_t h); // Constructor + + // This MUST be defined by the subclass: + virtual void drawPixel(int16_t x, int16_t y, uint16_t color) = 0; + + // These MAY be overridden by the subclass to provide device-specific + // optimized code. Otherwise 'generic' versions are used. + virtual void + drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, uint16_t color), + drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color), + drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color), + drawRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color), + fillRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color), + fillScreen(uint16_t color), + invertDisplay(boolean i); + + // These exist only with Adafruit_GFX (no subclass overrides) + void + drawCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color), + drawCircleHelper(int16_t x0, int16_t y0, int16_t r, uint8_t cornername, + uint16_t color), + fillCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color), + fillCircleHelper(int16_t x0, int16_t y0, int16_t r, uint8_t cornername, + int16_t delta, uint16_t color), + drawTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1, + int16_t x2, int16_t y2, uint16_t color), + fillTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1, + int16_t x2, int16_t y2, uint16_t color), + drawRoundRect(int16_t x0, int16_t y0, int16_t w, int16_t h, + int16_t radius, uint16_t color), + fillRoundRect(int16_t x0, int16_t y0, int16_t w, int16_t h, + int16_t radius, uint16_t color), + drawBitmap(int16_t x, int16_t y, const uint8_t *bitmap, + int16_t w, int16_t h, uint16_t color), + drawChar(int16_t x, int16_t y, unsigned char c, uint16_t color, + uint16_t bg, uint8_t size), + setCursor(int16_t x, int16_t y), + setTextColor(uint16_t c), + setTextColor(uint16_t c, uint16_t bg), + setTextSize(uint8_t s), + setTextWrap(boolean w), + setRotation(uint8_t r); + +#if ARDUINO >= 100 + virtual size_t write(uint8_t); +#else + virtual void write(uint8_t); +#endif + + int16_t + height(void), + width(void); + + uint8_t getRotation(void); + + + /* + * Processing-like graphics primitives + */ + + /// transforms a color in 16-bit form given the RGB components. + /// The default implementation makes a 5-bit red, a 6-bit + /// green and a 5-bit blue (MSB to LSB). Devices that use + /// different scheme should override this. + virtual uint16_t newColor(uint8_t red, uint8_t green, uint8_t blue); + + + // http://processing.org/reference/background_.html + void background(uint8_t red, uint8_t green, uint8_t blue); + void background(color c); + + // http://processing.org/reference/fill_.html + void fill(uint8_t red, uint8_t green, uint8_t blue); + void fill(color c); + + // http://processing.org/reference/noFill_.html + void noFill(); + + // http://processing.org/reference/stroke_.html + void stroke(uint8_t red, uint8_t green, uint8_t blue); + void stroke(color c); + + // http://processing.org/reference/noStroke_.html + void noStroke(); + + void text(const char * text, int16_t x, int16_t y); + void text(int value, uint8_t posX, uint8_t posY); + void text(long value, uint8_t posX, uint8_t posY); + void text(char value, uint8_t posX, uint8_t posY); + + void textWrap(const char * text, int16_t x, int16_t y); + + void textSize(uint8_t size); + + // similar to ellipse() in Processing, but with + // a single radius. + // http://processing.org/reference/ellipse_.html + void circle(int16_t x, int16_t y, int16_t r); + + void point(int16_t x, int16_t y); + + void line(int16_t x1, int16_t y1, int16_t x2, int16_t y2); + + void quad(int16_t x1, int16_t y1, int16_t x2, int16_t y2, int16_t x3, int16_t y3, int16_t x4, int16_t y4); + + void rect(int16_t x, int16_t y, int16_t width, int16_t height); + + void rect(int16_t x, int16_t y, int16_t width, int16_t height, int16_t radius); + + void triangle(int16_t x1, int16_t y1, int16_t x2, int16_t y2, int16_t x3, int16_t y3); + + /* TODO + void rectMode(RectMode mode); + + void pushStyle(); + void popStyle(); + */ + +// PImage loadImage(const char * fileName) { return PImage::loadImage(fileName); } + +// void image(PImage & img, uint16_t x, uint16_t y); + + protected: + const int16_t + WIDTH, HEIGHT; // This is the 'raw' display w/h - never changes + int16_t + _width, _height, // Display w/h as modified by current rotation + cursor_x, cursor_y; + uint16_t + textcolor, textbgcolor; + uint8_t + textsize, + rotation; + boolean + wrap; // If set, 'wrap' text at right edge of display + + /* + * Processing-style graphics state + */ + + color strokeColor; + bool useStroke; + color fillColor; + bool useFill; +}; + +#endif // _ADAFRUIT_GFX_H diff --git a/libraries/Robot_Control/utility/RobotTextManager.cpp b/libraries/Robot_Control/utility/RobotTextManager.cpp new file mode 100644 index 00000000000..b516409ac98 --- /dev/null +++ b/libraries/Robot_Control/utility/RobotTextManager.cpp @@ -0,0 +1,192 @@ +#include +#include +#include "VirtualKeyboard.h" +#include "RobotTextManager.h" +#include "scripts_Hello_User.h" + +const int TextManager::lineHeight=10; +const int TextManager::charWidth=6; + + +void TextManager::setMargin(int margin_left,int margin_top){ + this->margin_left=margin_left; + this->margin_top=margin_top; +} +int TextManager::getLin(int lineNum){ + return lineNum*lineHeight+margin_top; +} + +int TextManager::getCol(int colNum){ + return colNum*charWidth+margin_left; +} + +void TextManager::writeText(int lineNum, int colNum, char* txt, bool onOff){ + if(!onOff) + Robot.setTextColor(WHITE); + + Robot.setCursor(getCol(colNum),getLin(lineNum)); + Robot.print(txt); + + Robot.setTextColor(BLACK); +} + +void TextManager::drawInput(bool onOff){ + if(!onOff) + Robot.setTextColor(WHITE); + + Robot.setCursor(getCol(inputCol),getLin(inputLin)+1); + Robot.print('_'); + + Robot.setTextColor(BLACK); + +} + +void TextManager::mvInput(int dire){ + drawInput(0); + if(dire<0){ + if(inputPos>0){ + inputPos--; + inputCol--; + } + }else{ + if(inputPos<16){ + inputPos++; + inputCol++; + } + } + drawInput(1); +} + +char TextManager::selectLetter(){ + static int oldVal; + char val=map(Robot.knobRead(),0,1023,32,125); + if(val==oldVal){ + return 0; //No changes + }else{ + oldVal=val; + return val; //Current letter + } +} + +void TextManager::refreshCurrentLetter(char letter){ + if(letter){ + writeText(inputLin,inputCol,inputPool+inputPos,false);//erase + inputPool[inputPos]=letter; + writeText(inputLin,inputCol,inputPool+inputPos,true);//write + } +} + + +void TextManager::getInput(int lin, int col){ + writeText(lin,col,">"); //Input indicator + + writeText(lin, col+1, inputPool); + + inputLin=lin; //Ini input cursor + inputCol=col+1; + inputPos=0; + drawInput(true); + + Vkey.display(100);//Vkey is a object of VirtualKeyboard class + + while(true){ + switch(Robot.keyboardRead()){ + case BUTTON_LEFT: + //Robot.beep(BEEP_SIMPLE); + mvInput(-1); + break; + case BUTTON_RIGHT: + //Robot.beep(BEEP_SIMPLE); + mvInput(1); + break; + case BUTTON_MIDDLE: + //Robot.beep(BEEP_DOUBLE); + char selection=Vkey.getSelection(); + if(selection!='\0'){ + refreshCurrentLetter(selection); + mvInput(1); + }else{ + drawInput(false); + return; + } + } + Vkey.run(); + delay(10); + } +} +void TextManager::setInputPool(int code){ + switch(code){ + case USERNAME: + Robot.userNameRead(inputPool); + break; + case ROBOTNAME: + Robot.robotNameRead(inputPool); + break; + case CITYNAME: + Robot.cityNameRead(inputPool); + break; + case COUNTRYNAME: + Robot.countryNameRead(inputPool); + break; + } + for(int i=0;i<18;i++){ + if(inputPool[i]=='\0'){ + for(int j=i;j<18;j++){ + inputPool[j]='\0'; + } + break; + } + } +} +void TextManager::pushInput(int code){ + switch(code){ + case USERNAME: + Robot.userNameWrite(inputPool); + break; + case ROBOTNAME: + Robot.robotNameWrite(inputPool); + break; + case CITYNAME: + Robot.cityNameWrite(inputPool); + break; + case COUNTRYNAME: + Robot.countryNameWrite(inputPool); + break; + } + for(int i=0;i<18;i++){ + inputPool[i]='\0'; + } +} +void TextManager::input(int lin,int col, int code){ + setInputPool(code); + getInput(lin,col); + pushInput(code); +} + +void TextManager::showPicture(char * filename, int posX, int posY){ + Robot.pause(); + Robot._drawBMP(filename,posX,posY); + Robot.play(); +} + +void TextManager::getPGMtext(int seq){ + //It takes a string from program space, and fill it + //in the buffer + //if(in hello user example){ + if(true){ + strcpy_P(PGMbuffer,(char*)pgm_read_word(&(::scripts_Hello_User[seq]))); + } +} + +void TextManager::writeScript(int seq, int line, int col){ + //print a string from program space to a specific line, + //column on the LCD + + //first fill the buffer with text from program space + getPGMtext(seq); + //then print it to the screen + textManager.writeText(line,col,PGMbuffer); +} + + +TextManager textManager=TextManager(); diff --git a/libraries/Robot_Control/utility/RobotTextManager.h b/libraries/Robot_Control/utility/RobotTextManager.h new file mode 100644 index 00000000000..6c0b7bde6ed --- /dev/null +++ b/libraries/Robot_Control/utility/RobotTextManager.h @@ -0,0 +1,77 @@ +#ifndef ROBOTTEXTMANAGER_H +#define ROBOTTEXTMANAGER_H + +#define USERNAME 0 +#define ROBOTNAME 1 +#define CITYNAME 2 +#define COUNTRYNAME 3 +#define EMPTY 4 + +class TextManager{ + //The TextManager class is a collection of features specific for Hello + //User example. + // + //- It includes solution for setting text position based on + // line/column. The original Robot.text(), or the more low level + // print() function can only set text position on pixels from left, + // top. + // + //- The process of accepting input with the virtual keyboard, saving + // into or reading from EEPROM is delt with here. + // + //- A workflow for stop the music while displaying image. Trouble + // will happen otherwise. + + public: + //add some margin to the text, left side only atm. + void setMargin(int margin_left,int margin_top); + + //print text based on line, column. + void writeText(int lineNum, int colNum, char* txt, bool onOff=true); + + //print a script from the scripts library + void writeScript(int seq, int line, int col); + + //The whole process of getting input + void input(int lin,int col, int code); + //Print a cursor and virtual keyboard on screen, and save the user's input + void getInput(int lin, int col); + //Get user name, robot name, city name or country name from EEPROM + //and store in the input pool. + void setInputPool(int code); + //save user input to EEPROM + void pushInput(int code); + + //Replaces Robot.drawPicture(), as this one solves collision between + //image and music + void showPicture(char * filename, int posX, int posY); + + private: + int margin_left,margin_top; + int getLin(int lineNum); //Convert line to pixels from top + int getCol(int colNum); //Convert line to pixels from left + + static const int lineHeight;//8+2=10 + static const int charWidth;//5+1=6 + + int inputPos; + int inputLin; + int inputCol; + + void drawInput(bool onOff); + void mvInput(int dire); + + char selectLetter(); + void refreshCurrentLetter(char letter); + + void getPGMtext(int seq); + + char PGMbuffer[85]; //the buffer for storing strings + char inputPool[18]; +}; + +//a trick for removing the need of creating an object of TextManager. +//So you can call me.somefunction() directly in the sketch. +extern TextManager textManager; + +#endif diff --git a/libraries/Robot_Control/utility/VirtualKeyboard.cpp b/libraries/Robot_Control/utility/VirtualKeyboard.cpp new file mode 100644 index 00000000000..ad73c7519b7 --- /dev/null +++ b/libraries/Robot_Control/utility/VirtualKeyboard.cpp @@ -0,0 +1,127 @@ +#include "VirtualKeyboard.h" + +int VirtualKeyboard::getColLin(int val){ + uint8_t col,lin; + lin=val/10; + col=val%10; // saving 36 bytes :( + /*if(0<=val && 9>=val){ + col=val; + lin=0; + }else if(10<=val && 19>=val){ + col=val-10; + lin=1; + }else if(20<=val && 29>=val){ + col=val-20; + lin=2; + }else if(30<=val && 39>=val){ + col=val-30; + lin=3; + }*/ + return (col<<8)+lin; //Put col and lin in one int +} +void VirtualKeyboard::run(){ +/** visually select a letter on the keyboard +* The selection boarder is 1px higher than the character, +* 1px on the bottom, 2px to the left and 2px to the right. +* +*/ + if(!onOff)return; + //Serial.println(onOff); + static int oldColLin=0; + uint8_t val=map(Robot.knobRead(),0,1023,0,38); + if(val==38)val=37; //The last value is jumpy when using batteries + int colLin=getColLin(val); + + if(oldColLin!=colLin){ + uint8_t x=(oldColLin>>8 & 0xFF)*11+10;//col*11+1+9 + uint8_t y=(oldColLin & 0xFF)*11+1+top;//lin*11+1+top + uint8_t w=9; + if(oldColLin==1795) //last item "Enter", col=7 lin=3 + w=33; //(5+1)*6-1+2+2 charWidth=5, charMargin=1, count("Enter")=6, lastItem_MarginRight=0, marginLeft==marginRight=2 + Robot.drawRect(x,y,w,9,hideColor); + + + x=(colLin>>8 & 0xFF)*11+10; + y=(colLin & 0xFF)*11+1+top; + w=9; + if(colLin==1795) //last item "Enter", col=7 lin=3 + w=33; //(5+1)*6-1+2+2 charWidth=5, charMargin=1, count("Enter")=6, lastItem_MarginRight=0, marginLeft==marginRight=2 + Robot.drawRect(x,y,w,9,showColor); + oldColLin=colLin; + } +} + +char VirtualKeyboard::getSelection(){ + if(!onOff)return -1; + + uint8_t val=map(Robot.knobRead(),0,1023,0,38); + if(0<=val && 9>=val) + val='0'+val; + else if(10<=val && 35>=val) + val='A'+val-10; + else if(val==36) + val=' '; + else if(val>=37) + val='\0'; + + return val; +} +void VirtualKeyboard::hide(){ + onOff=false; + Robot.fillRect(0,top,128,44,hideColor);//11*4 +} + +void VirtualKeyboard::display(uint8_t top, uint16_t showColor, uint16_t hideColor){ +/** Display the keyboard at y position of top +* formular: +* When text size is 1, one character is 5*7 +* margin-left==margin-right==3, +* margin-top==margin-bottom==2, +* keyWidth=5+3+3==11, +* keyHeight=7+2+2==11, +* keyboard-margin-left=keyboard-margin-right==9 +* so character-x=11*col+9+3=11*col+12 +* character-y=11*lin+2+top +* +**/ + this->top=top; + this->onOff=true; + + this->showColor=showColor; + this->hideColor=hideColor; + + for(uint8_t i=0;i<36;i++){ + Robot.setCursor(i%10*11+12,2+top+i/10*11); + if(i<10) + Robot.print(char('0'+i)); + else + Robot.print(char(55+i));//'A'-10=55 + }//for saving 58 bytes :( + + /*for(int i=0;i<10;i++){ + Robot.setCursor(i*11+12,2+top);//11*0+2+top + Robot.print(char('0'+i));//line_1: 0-9 + } + for(int i=0;i<10;i++){ + Robot.setCursor(i*11+12,13+top);//11*1+2+top + Robot.print(char('A'+i));//line_2: A-J + } + for(int i=0;i<10;i++){ + Robot.setCursor(i*11+12,24+top);//11*2+2+top + Robot.print(char('K'+i));//line_3: K-T + } + for(int i=0;i<6;i++){ + Robot.setCursor(i*11+12,35+top);//11*3+2+top + Robot.print(char('U'+i));//line_4: U-Z + }*/ + //space and enter at the end of the last line. + Robot.setCursor(78,35+top);//6*11+12=78 + Robot.print('_');//_ + + Robot.setCursor(89,35+top);//7*11+12=89 + Robot.print("Enter");//enter +} + + + +VirtualKeyboard Vkey=VirtualKeyboard(); \ No newline at end of file diff --git a/libraries/Robot_Control/utility/VirtualKeyboard.h b/libraries/Robot_Control/utility/VirtualKeyboard.h new file mode 100644 index 00000000000..273edb724eb --- /dev/null +++ b/libraries/Robot_Control/utility/VirtualKeyboard.h @@ -0,0 +1,28 @@ +#ifndef VIRTUAL_KEYBOARD_H +#define VIRTUAL_KEYBOARD_H + +#include +#include + +class VirtualKeyboard{ + public: + //void begin(); + void display(uint8_t top, uint16_t showColor=BLACK, uint16_t hideColor=WHITE); + void hide(); + + char getSelection(); + void run(); + + private: + uint8_t top; + bool onOff; + + uint16_t showColor; + uint16_t hideColor; + + int getColLin(int val); + +}; + +extern VirtualKeyboard Vkey; +#endif \ No newline at end of file diff --git a/libraries/Robot_Control/utility/scripts_Hello_User.h b/libraries/Robot_Control/utility/scripts_Hello_User.h new file mode 100644 index 00000000000..29f085f1cf4 --- /dev/null +++ b/libraries/Robot_Control/utility/scripts_Hello_User.h @@ -0,0 +1,51 @@ +#include + +//an advanced trick for storing strings inside the program space +//as the ram of Arduino is very tiny, keeping too many string in it +//can kill the program + +prog_char hello_user_script1[] PROGMEM="What's your name?"; +prog_char hello_user_script2[] PROGMEM="Give me a name!"; +prog_char hello_user_script3[] PROGMEM="And the country?"; +prog_char hello_user_script4[] PROGMEM="The city you're in?"; +prog_char hello_user_script5[] PROGMEM=" Plug me to\n\n your computer\n\n and start coding!"; + +prog_char hello_user_script6[] PROGMEM=" Hello User!\n\n It's me, your robot\n\n I'm alive! <3"; +prog_char hello_user_script7[] PROGMEM=" First I need some\n\n input from you!"; +prog_char hello_user_script8[] PROGMEM=" Use the knob\n\n to select letters"; +prog_char hello_user_script9[] PROGMEM=" Use L/R button\n\n to move the cursor,\n\n middle to confirm"; +prog_char hello_user_script10[] PROGMEM=" Press middle key\n to continue..."; +prog_char hello_user_script11[] PROGMEM=" Choose \"enter\" to\n\n finish the input"; + +PROGMEM const char *scripts_Hello_User[]={ + hello_user_script1, + hello_user_script2, + hello_user_script3, + hello_user_script4, + hello_user_script5, + hello_user_script6, + hello_user_script7, + hello_user_script8, + hello_user_script9, + hello_user_script10, + hello_user_script11, +}; + +/* +void getPGMtext(int seq){ + //It takes a string from program space, and fill it + //in the buffer + strcpy_P(buffer,(char*)pgm_read_word(&(scripts[seq]))); +} + +void writeScript(int seq, int line, int col){ + //print a string from program space to a specific line, + //column on the LCD + + //first fill the buffer with text from program space + getPGMtext(seq); + //then print it to the screen + textManager.writeText(line,col,buffer); +} + +*/ \ No newline at end of file diff --git a/libraries/Robot_Motor/ArduinoRobotMotorBoard.cpp b/libraries/Robot_Motor/ArduinoRobotMotorBoard.cpp new file mode 100644 index 00000000000..4d795e06116 --- /dev/null +++ b/libraries/Robot_Motor/ArduinoRobotMotorBoard.cpp @@ -0,0 +1,269 @@ +#include "ArduinoRobotMotorBoard.h" +#include "EasyTransfer2.h" +#include "Multiplexer.h" +#include "LineFollow.h" + +RobotMotorBoard::RobotMotorBoard(){ + //LineFollow::LineFollow(); +} +/*void RobotMotorBoard::beginIRReceiver(){ + IRrecv::enableIRIn(); +}*/ +void RobotMotorBoard::begin(){ + //initialze communication + Serial1.begin(9600); + messageIn.begin(&Serial1); + messageOut.begin(&Serial1); + + //init MUX + uint8_t MuxPins[]={MUXA,MUXB,MUXC}; + this->IRs.begin(MuxPins,MUX_IN,3); + pinMode(MUXI,INPUT); + digitalWrite(MUXI,LOW); + + isPaused=false; +} + +void RobotMotorBoard::process(){ + if(isPaused)return;//skip process if the mode is paused + + if(mode==MODE_SIMPLE){ + //Serial.println("s"); + //do nothing? Simple mode is just about getting commands + }else if(mode==MODE_LINE_FOLLOW){ + //do line following stuff here. + LineFollow::runLineFollow(); + }else if(mode==MODE_ADJUST_MOTOR){ + //Serial.println('a'); + //motorAdjustment=analogRead(POT); + //setSpeed(255,255); + //delay(100); + } +} +void RobotMotorBoard::pauseMode(bool onOff){ + if(onOff){ + isPaused=true; + }else{ + isPaused=false; + } + stopCurrentActions(); + +} +void RobotMotorBoard::parseCommand(){ + uint8_t modeName; + uint8_t codename; + int value; + int speedL; + int speedR; + if(this->messageIn.receiveData()){ + //Serial.println("data received"); + uint8_t command=messageIn.readByte(); + //Serial.println(command); + switch(command){ + case COMMAND_SWITCH_MODE: + modeName=messageIn.readByte(); + setMode(modeName); + break; + case COMMAND_RUN: + if(mode==MODE_LINE_FOLLOW)break;//in follow line mode, the motor does not follow commands + speedL=messageIn.readInt(); + speedR=messageIn.readInt(); + motorsWrite(speedL,speedR); + break; + case COMMAND_MOTORS_STOP: + motorsStop(); + break; + case COMMAND_ANALOG_WRITE: + codename=messageIn.readByte(); + value=messageIn.readInt(); + _analogWrite(codename,value); + break; + case COMMAND_DIGITAL_WRITE: + codename=messageIn.readByte(); + value=messageIn.readByte(); + _digitalWrite(codename,value); + break; + case COMMAND_ANALOG_READ: + codename=messageIn.readByte(); + _analogRead(codename); + break; + case COMMAND_DIGITAL_READ: + codename=messageIn.readByte(); + _digitalRead(codename); + break; + case COMMAND_READ_IR: + _readIR(); + break; + case COMMAND_READ_TRIM: + _readTrim(); + break; + case COMMAND_PAUSE_MODE: + pauseMode(messageIn.readByte());//onOff state + break; + case COMMAND_LINE_FOLLOW_CONFIG: + LineFollow::config( + messageIn.readByte(), //KP + messageIn.readByte(), //KD + messageIn.readByte(), //robotSpeed + messageIn.readByte() //IntegrationTime + ); + break; + } + } + //delay(5); +} +uint8_t RobotMotorBoard::parseCodename(uint8_t codename){ + switch(codename){ + case B_TK1: + return TK1; + case B_TK2: + return TK2; + case B_TK3: + return TK3; + case B_TK4: + return TK4; + } +} +uint8_t RobotMotorBoard::codenameToAPin(uint8_t codename){ + switch(codename){ + case B_TK1: + return A0; + case B_TK2: + return A1; + case B_TK3: + return A6; + case B_TK4: + return A11; + } +} + +void RobotMotorBoard::setMode(uint8_t mode){ + if(mode==MODE_LINE_FOLLOW){ + LineFollow::calibIRs(); + } + /*if(mode==SET_MOTOR_ADJUSTMENT){ + save_motor_adjustment_to_EEPROM(); + } + */ + /*if(mode==MODE_IR_CONTROL){ + beginIRReceiver(); + }*/ + this->mode=mode; + //stopCurrentActions();//If line following, this should stop the motors +} + +void RobotMotorBoard::stopCurrentActions(){ + motorsStop(); + //motorsWrite(0,0); +} + +void RobotMotorBoard::motorsWrite(int speedL, int speedR){ + /*Serial.print(speedL); + Serial.print(" "); + Serial.println(speedR);*/ + //motor adjustment, using percentage + _refreshMotorAdjustment(); + + if(motorAdjustment<0){ + speedR*=(1+motorAdjustment); + }else{ + speedL*=(1-motorAdjustment); + } + + if(speedR>0){ + analogWrite(IN_A1,speedR); + analogWrite(IN_A2,0); + }else{ + analogWrite(IN_A1,0); + analogWrite(IN_A2,-speedR); + } + + if(speedL>0){ + analogWrite(IN_B1,speedL); + analogWrite(IN_B2,0); + }else{ + analogWrite(IN_B1,0); + analogWrite(IN_B2,-speedL); + } +} +void RobotMotorBoard::motorsWritePct(int speedLpct, int speedRpct){ + //speedLpct, speedRpct ranges from -100 to 100 + motorsWrite(speedLpct*2.55,speedRpct*2.55); +} +void RobotMotorBoard::motorsStop(){ + analogWrite(IN_A1,255); + analogWrite(IN_A2,255); + + analogWrite(IN_B1,255); + analogWrite(IN_B2,255); +} + + +/* +* +* +* Input and Output ports +* +* +*/ +void RobotMotorBoard::_digitalWrite(uint8_t codename,bool value){ + uint8_t pin=parseCodename(codename); + digitalWrite(pin,value); +} +void RobotMotorBoard::_analogWrite(uint8_t codename,int value){ + //There's no PWM available on motor board +} +void RobotMotorBoard::_digitalRead(uint8_t codename){ + uint8_t pin=parseCodename(codename); + bool value=digitalRead(pin); + messageOut.writeByte(COMMAND_DIGITAL_READ_RE); + messageOut.writeByte(codename); + messageOut.writeByte(value); + messageOut.sendData(); +} +void RobotMotorBoard::_analogRead(uint8_t codename){ + uint8_t pin=codenameToAPin(codename); + int value=analogRead(pin); + messageOut.writeByte(COMMAND_ANALOG_READ_RE); + messageOut.writeByte(codename); + messageOut.writeInt(value); + messageOut.sendData(); +} +int RobotMotorBoard::IRread(uint8_t num){ + return _IRread(num-1); //To make consistant with the pins labeled on the board +} + +int RobotMotorBoard::_IRread(uint8_t num){ + IRs.selectPin(num); + return IRs.getAnalogValue(); +} + + +void RobotMotorBoard::_readIR(){ + int value; + messageOut.writeByte(COMMAND_READ_IR_RE); + for(int i=0;i<5;i++){ + value=_IRread(i); + messageOut.writeInt(value); + } + messageOut.sendData(); +} + +void RobotMotorBoard::_readTrim(){ + int value=analogRead(TRIM); + messageOut.writeByte(COMMAND_READ_TRIM_RE); + messageOut.writeInt(value); + messageOut.sendData(); +} + +void RobotMotorBoard::_refreshMotorAdjustment(){ + motorAdjustment=map(analogRead(TRIM),0,1023,-30,30)/100.0; +} + +void RobotMotorBoard::reportActionDone(){ + setMode(MODE_SIMPLE); + messageOut.writeByte(COMMAND_ACTION_DONE); + messageOut.sendData(); +} + +RobotMotorBoard RobotMotor=RobotMotorBoard(); \ No newline at end of file diff --git a/libraries/Robot_Motor/ArduinoRobotMotorBoard.h b/libraries/Robot_Motor/ArduinoRobotMotorBoard.h new file mode 100644 index 00000000000..2bbc8ea8a4a --- /dev/null +++ b/libraries/Robot_Motor/ArduinoRobotMotorBoard.h @@ -0,0 +1,126 @@ +#ifndef ArduinoRobot_h +#define ArduinoRobot_h + +#include "EasyTransfer2.h" +#include "Multiplexer.h" +#include "LineFollow.h" +//#include "IRremote.h" + +#if ARDUINO >= 100 +#include "Arduino.h" +#else +#include "WProgram.h" +#endif + +//Command code +#define COMMAND_SWITCH_MODE 0 +#define COMMAND_RUN 10 +#define COMMAND_MOTORS_STOP 11 +#define COMMAND_ANALOG_WRITE 20 +#define COMMAND_DIGITAL_WRITE 30 +#define COMMAND_ANALOG_READ 40 +#define COMMAND_ANALOG_READ_RE 41 +#define COMMAND_DIGITAL_READ 50 +#define COMMAND_DIGITAL_READ_RE 51 +#define COMMAND_READ_IR 60 +#define COMMAND_READ_IR_RE 61 +#define COMMAND_ACTION_DONE 70 +#define COMMAND_READ_TRIM 80 +#define COMMAND_READ_TRIM_RE 81 +#define COMMAND_PAUSE_MODE 90 +#define COMMAND_LINE_FOLLOW_CONFIG 100 + + +//component codename +#define CN_LEFT_MOTOR 0 +#define CN_RIGHT_MOTOR 1 +#define CN_IR 2 + +//motor board modes +#define MODE_SIMPLE 0 +#define MODE_LINE_FOLLOW 1 +#define MODE_ADJUST_MOTOR 2 +#define MODE_IR_CONTROL 3 + +//bottom TKs, just for communication purpose +#define B_TK1 201 +#define B_TK2 202 +#define B_TK3 203 +#define B_TK4 204 + +/* +A message structure will be: +switch mode (2): + byte COMMAND_SWITCH_MODE, byte mode +run (5): + byte COMMAND_RUN, int speedL, int speedR +analogWrite (3): + byte COMMAND_ANALOG_WRITE, byte codename, byte value; +digitalWrite (3): + byte COMMAND_DIGITAL_WRITE, byte codename, byte value; +analogRead (2): + byte COMMAND_ANALOG_READ, byte codename; +analogRead _return_ (4): + byte COMMAND_ANALOG_READ_RE, byte codename, int value; +digitalRead (2): + byte COMMAND_DIGITAL_READ, byte codename; +digitalRead _return_ (4): + byte COMMAND_DIGITAL_READ_RE, byte codename, int value; +read IR (1): + byte COMMAND_READ_IR; +read IR _return_ (9): + byte COMMAND_READ_IR_RE, int valueA, int valueB, int valueC, int valueD; + + +*/ + +class RobotMotorBoard:public LineFollow{ + public: + RobotMotorBoard(); + void begin(); + + void process(); + + void parseCommand(); + + int IRread(uint8_t num); + + void setMode(uint8_t mode); + void pauseMode(bool onOff); + + void motorsWrite(int speedL, int speedR); + void motorsWritePct(int speedLpct, int speedRpct);//write motor values in percentage + void motorsStop(); + private: + float motorAdjustment;//-1.0 ~ 1.0, whether left is lowered or right is lowered + + //convert codename to actual pins + uint8_t parseCodename(uint8_t codename); + uint8_t codenameToAPin(uint8_t codename); + + void stopCurrentActions(); + //void sendCommand(byte command,byte codename,int value); + + void _analogWrite(uint8_t codename, int value); + void _digitalWrite(uint8_t codename, bool value); + void _analogRead(uint8_t codename); + void _digitalRead(uint8_t codename); + int _IRread(uint8_t num); + void _readIR(); + void _readTrim(); + + void _refreshMotorAdjustment(); + + Multiplexer IRs; + uint8_t mode; + uint8_t isPaused; + EasyTransfer2 messageIn; + EasyTransfer2 messageOut; + + //Line Following + void reportActionDone(); +}; + +extern RobotMotorBoard RobotMotor; + +#endif \ No newline at end of file diff --git a/libraries/Robot_Motor/EasyTransfer2.cpp b/libraries/Robot_Motor/EasyTransfer2.cpp new file mode 100644 index 00000000000..24427cc6e71 --- /dev/null +++ b/libraries/Robot_Motor/EasyTransfer2.cpp @@ -0,0 +1,152 @@ +#include "EasyTransfer2.h" + + + + +//Captures address and size of struct +void EasyTransfer2::begin(HardwareSerial *theSerial){ + _serial = theSerial; + + //dynamic creation of rx parsing buffer in RAM + //rx_buffer = (uint8_t*) malloc(size); + + resetData(); +} + +void EasyTransfer2::writeByte(uint8_t dat){ + if(position<20) + data[position++]=dat; + size++; +} +void EasyTransfer2::writeInt(int dat){ + if(position<19){ + data[position++]=dat>>8; + data[position++]=dat; + size+=2; + } +} +uint8_t EasyTransfer2::readByte(){ + if(position>=size)return 0; + return data[position++]; +} +int EasyTransfer2::readInt(){ + if(position+1>=size)return 0; + int dat_1=data[position++]<<8; + int dat_2=data[position++]; + int dat= dat_1 | dat_2; + return dat; +} + +void EasyTransfer2::resetData(){ + for(int i=0;i<20;i++){ + data[i]=0; + } + size=0; + position=0; +} + +//Sends out struct in binary, with header, length info and checksum +void EasyTransfer2::sendData(){ + uint8_t CS = size; + _serial->write(0x06); + _serial->write(0x85); + _serial->write(size); + for(int i = 0; iwrite(*(data+i)); + //Serial.print(*(data+i)); + //Serial.print(","); + } + //Serial.println(""); + _serial->write(CS); + + resetData(); +} + +boolean EasyTransfer2::receiveData(){ + + //start off by looking for the header bytes. If they were already found in a previous call, skip it. + if(rx_len == 0){ + //this size check may be redundant due to the size check below, but for now I'll leave it the way it is. + if(_serial->available() >= 3){ + //this will block until a 0x06 is found or buffer size becomes less then 3. + while(_serial->read() != 0x06) { + //This will trash any preamble junk in the serial buffer + //but we need to make sure there is enough in the buffer to process while we trash the rest + //if the buffer becomes too empty, we will escape and try again on the next call + if(_serial->available() < 3) + return false; + } + //Serial.println("head"); + if (_serial->read() == 0x85){ + rx_len = _serial->read(); + //Serial.print("rx_len:"); + //Serial.println(rx_len); + resetData(); + + //make sure the binary structs on both Arduinos are the same size. + /*if(rx_len != size){ + rx_len = 0; + return false; + }*/ + } + } + //Serial.println("nothing"); + } + + //we get here if we already found the header bytes, the struct size matched what we know, and now we are byte aligned. + if(rx_len != 0){ + + while(_serial->available() && rx_array_inx <= rx_len){ + data[rx_array_inx++] = _serial->read(); + } + + if(rx_len == (rx_array_inx-1)){ + //seem to have got whole message + //last uint8_t is CS + calc_CS = rx_len; + //Serial.print("len:"); + //Serial.println(rx_len); + for (int i = 0; i +* +*This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License. +*To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/ or +*send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA. +******************************************************************/ +#ifndef EasyTransfer2_h +#define EasyTransfer2_h + + +//make it a little prettier on the front end. +#define details(name) (byte*)&name,sizeof(name) + +//Not neccessary, but just in case. +#if ARDUINO > 22 +#include "Arduino.h" +#else +#include "WProgram.h" +#endif +#include "HardwareSerial.h" +//#include +#include +#include +#include +#include + +class EasyTransfer2 { +public: +void begin(HardwareSerial *theSerial); +//void begin(uint8_t *, uint8_t, NewSoftSerial *theSerial); +void sendData(); +boolean receiveData(); + +void writeByte(uint8_t dat); +void writeInt(int dat); +uint8_t readByte(); +int readInt(); + + +private: +HardwareSerial *_serial; + +void resetData(); + +uint8_t data[20]; //data storage, for both read and send +uint8_t position; +uint8_t size; //size of data in bytes. Both for read and send +//uint8_t * address; //address of struct +//uint8_t size; //size of struct +//uint8_t * rx_buffer; //address for temporary storage and parsing buffer +//uint8_t rx_buffer[20]; +uint8_t rx_array_inx; //index for RX parsing buffer +uint8_t rx_len; //RX packet length according to the packet +uint8_t calc_CS; //calculated Chacksum +}; + + + +#endif \ No newline at end of file diff --git a/libraries/Robot_Motor/LineFollow.h b/libraries/Robot_Motor/LineFollow.h new file mode 100644 index 00000000000..8c5bc496efd --- /dev/null +++ b/libraries/Robot_Motor/LineFollow.h @@ -0,0 +1,40 @@ +#ifndef LINE_FOLLOW_H +#define LINE_FOLLOW_H + +#if ARDUINO >= 100 + #include "Arduino.h" +#else + #include "WProgram.h" +#endif + +class LineFollow{ + public: + LineFollow(); + + void calibIRs(); + void runLineFollow(); + void config(uint8_t KP, uint8_t KD, uint8_t robotSpeed, uint8_t intergrationTime); + + //These are all pure virtual functions, pure VF needs pure specifier "=0" + //virtual void motorsWrite(int speedL, int speedR)=0; + virtual void motorsWritePct(int speedLpct, int speedRpct)=0; + virtual void motorsStop()=0; + virtual int _IRread(uint8_t num)=0; + protected: + virtual void reportActionDone()=0; + + private: + void doCalibration(int speedPct, int time); + void ajusta_niveles(); + + uint8_t KP; + uint8_t KD; + uint8_t robotSpeed; //percentage + uint8_t intergrationTime; + + int lectura_sensor[5], last_error, acu; + int sensor_blanco[5]; + int sensor_negro[5]; +}; + +#endif \ No newline at end of file diff --git a/libraries/Robot_Motor/Multiplexer.cpp b/libraries/Robot_Motor/Multiplexer.cpp new file mode 100644 index 00000000000..c0fdd867fbc --- /dev/null +++ b/libraries/Robot_Motor/Multiplexer.cpp @@ -0,0 +1,37 @@ +#include "Multiplexer.h" + +void Multiplexer::begin(uint8_t* selectors, uint8_t Z, uint8_t length){ + for(uint8_t i=0;iselectors[i]=selectors[i]; + pinMode(selectors[i],OUTPUT); + } + this->length=length; + this->pin_Z=Z; + pinMode(pin_Z,INPUT); +} + +void Multiplexer::selectPin(uint8_t num){ + for(uint8_t i=0;i= 100 +#include "Arduino.h" +#else +#include "WProgram.h" +#endif + +class Multiplexer{ + public: + void begin(uint8_t* selectors, uint8_t Z, uint8_t length); + void selectPin(uint8_t num); + int getAnalogValue(); + int getAnalogValueAt(uint8_t num); + bool getDigitalValue(); + bool getDigitalValueAt(uint8_t num); + private: + uint8_t selectors[4]; + uint8_t pin_Z; + uint8_t length; +}; + +#endif diff --git a/libraries/Robot_Motor/examples/Robot_IR_Array_Test/Robot_IR_Array_Test.ino b/libraries/Robot_Motor/examples/Robot_IR_Array_Test/Robot_IR_Array_Test.ino new file mode 100644 index 00000000000..160097e952e --- /dev/null +++ b/libraries/Robot_Motor/examples/Robot_IR_Array_Test/Robot_IR_Array_Test.ino @@ -0,0 +1,26 @@ +/* Motor Board IR Array Test + + This example of the Arduno robot's motor board returns the + values read fron the 5 infrared sendors on the bottom of + the robot. + +*/ +// include the motor board header +#include + +String bar; // string for storing the informaton + +void setup(){ + // start serial communication + Serial.begin(9600); + // initialize the library + RobotMotor.begin(); +} +void loop(){ + bar=String(""); // empty the string + // read the sensors and add them to the string + bar=bar+RobotMotor.IRread(1)+' '+RobotMotor.IRread(2)+' '+RobotMotor.IRread(3)+' '+RobotMotor.IRread(4)+' '+RobotMotor.IRread(5); + // print out the values + Serial.println(bar); + delay(100); +} diff --git a/libraries/Robot_Motor/examples/Robot_Motor_Core/Robot_Motor_Core.ino b/libraries/Robot_Motor/examples/Robot_Motor_Core/Robot_Motor_Core.ino new file mode 100644 index 00000000000..f74f30a299e --- /dev/null +++ b/libraries/Robot_Motor/examples/Robot_Motor_Core/Robot_Motor_Core.ino @@ -0,0 +1,18 @@ +/* Motor Core + + This code for the Arduino Robot's motor board + is the stock firmware. program the motor board with + this sketch whenever you want to return the motor + board to its default state. + +*/ + +#include + +void setup(){ + RobotMotor.begin(); +} +void loop(){ + RobotMotor.parseCommand(); + RobotMotor.process(); +} diff --git a/libraries/Robot_Motor/lineFollow.cpp b/libraries/Robot_Motor/lineFollow.cpp new file mode 100644 index 00000000000..71eacb5ad33 --- /dev/null +++ b/libraries/Robot_Motor/lineFollow.cpp @@ -0,0 +1,152 @@ +//#include +#include "LineFollow.h" + +//#define KP 19 //0.1 units +//#define KD 14 +//#define ROBOT_SPEED 100 //percentage + +//#define KP 11 +//#define KD 5 +//#define ROBOT_SPEED 50 + +//#define INTEGRATION_TIME 10 //En ms + +/*uint8_t KP=11; +uint8_t KD=5; +uint8_t robotSpeed=50; //percentage +uint8_t intergrationTime=10;*/ + +#define NIVEL_PARA_LINEA 50 + +/*int lectura_sensor[5], last_error=0, acu=0; + +//Estos son los arrays que hay que rellenar con los valores de los sensores +//de suelo sobre blanco y negro. +int sensor_blanco[]={ + 0,0,0,0,0}; +int sensor_negro[]={ + 1023,1023,1023,1023,1023}; +*/ +//unsigned long time; + +//void mueve_robot(int vel_izq, int vel_der); +//void para_robot(); +//void doCalibration(int speedPct, int time); +//void ajusta_niveles(); //calibrate values + +LineFollow::LineFollow(){ + /*KP=11; + KD=5; + robotSpeed=50; //percentage + intergrationTime=10;*/ + config(11,5,50,10); + + for(int i=0;i<5;i++){ + sensor_blanco[i]=0; + sensor_negro[i]=1023; + } +} + +void LineFollow::config(uint8_t KP, uint8_t KD, uint8_t robotSpeed, uint8_t intergrationTime){ + this->KP=KP; + this->KD=KD; + this->robotSpeed=robotSpeed; + this->intergrationTime=intergrationTime; + /*Serial.print("LFC: "); + Serial.print(KP); + Serial.print(' '); + Serial.print(KD); + Serial.print(' '); + Serial.print(robotSpeed); + Serial.print(' '); + Serial.println(intergrationTime);*/ + +} +void LineFollow::calibIRs(){ + static bool isInited=false;//So only init once + if(isInited)return ; + + delay(1000); + + doCalibration(30,500); + doCalibration(-30,800); + doCalibration(30,500); + + delay(1000); + isInited=true; +} + +void LineFollow::runLineFollow(){ + for(int count=0; count<5; count++) + { + lectura_sensor[count]=map(_IRread(count),sensor_negro[count],sensor_blanco[count],0,127); + acu+=lectura_sensor[count]; + } + + //Serial.println(millis()); + if (acu > NIVEL_PARA_LINEA) + { + acu/=5; + + int error = ((lectura_sensor[0]<<6)+(lectura_sensor[1]<<5)-(lectura_sensor[3]<<5)-(lectura_sensor[4]<<6))/acu; + + error = constrain(error,-100,100); + + //Calculamos la correcion de velocidad mediante un filtro PD + int vel = (error * KP)/10 + (error-last_error)*KD; + + last_error = error; + + //Corregimos la velocidad de avance con el error de salida del filtro PD + int motor_left = constrain((robotSpeed + vel),-100,100); + int motor_right =constrain((robotSpeed - vel),-100,100); + + //Movemos el robot + //motorsWritePct(motor_left,motor_right); + motorsWritePct(motor_left,motor_right); + + //Esperamos un poquito a que el robot reaccione + delay(intergrationTime); + } + else + { + //Hemos encontrado una linea negra + //perpendicular a nuestro camino + //paramos el robot + motorsStop(); + + //y detenemos la ejecuci�n del programa + //while(true); + reportActionDone(); + //setMode(MODE_SIMPLE); + } +} + + +void LineFollow::doCalibration(int speedPct, int time){ + motorsWritePct(speedPct, -speedPct); + unsigned long beginTime = millis(); + while((millis()-beginTime) sensor_blanco[count]) + sensor_blanco[count]=lectura; + + if (lectura < sensor_negro[count]) + sensor_negro[count]=lectura; + } +} + + + + + + diff --git a/libraries/SD/File.cpp b/libraries/SD/File.cpp index 88d9e9ac95e..6eee39aa1ff 100644 --- a/libraries/SD/File.cpp +++ b/libraries/SD/File.cpp @@ -43,10 +43,6 @@ File::File(void) { //Serial.print("Created empty file object"); } -File::~File(void) { - // Serial.print("Deleted file object"); -} - // returns a pointer to the file name char *File::name(void) { return _name; diff --git a/libraries/SD/SD.h b/libraries/SD/SD.h index f21ec0f29e3..7435cf5773d 100644 --- a/libraries/SD/SD.h +++ b/libraries/SD/SD.h @@ -31,7 +31,6 @@ class File : public Stream { public: File(SdFile f, const char *name); // wraps an underlying SdFile File(void); // 'empty' constructor - ~File(void); // destructor virtual size_t write(uint8_t); virtual size_t write(const uint8_t *buf, size_t size); virtual int read(); diff --git a/libraries/SD/examples/listfiles/listfiles.ino b/libraries/SD/examples/listfiles/listfiles.ino index d403073b6c2..2bf8e68713c 100644 --- a/libraries/SD/examples/listfiles/listfiles.ino +++ b/libraries/SD/examples/listfiles/listfiles.ino @@ -1,7 +1,9 @@ /* - SD card basic file example + Listfiles - This example shows how to create and destroy an SD card file + This example shows how print out the files in a + directory on a SD card + The circuit: * SD card attached to SPI bus as follows: ** MOSI - pin 11 @@ -13,6 +15,8 @@ by David A. Mellis modified 9 Apr 2012 by Tom Igoe + modified 2 Feb 2014 + by Scott Fitzgerald This example code is in the public domain. @@ -29,7 +33,6 @@ void setup() ; // wait for serial port to connect. Needed for Leonardo only } - Serial.print("Initializing SD card..."); // On the Ethernet Shield, CS is pin 4. It's set as an output by default. // Note that even if it's not used as the CS pin, the hardware SS pin @@ -37,7 +40,7 @@ void setup() // or the SD library functions will not work. pinMode(10, OUTPUT); - if (!SD.begin(10)) { + if (!SD.begin(4)) { Serial.println("initialization failed!"); return; } @@ -61,7 +64,6 @@ void printDirectory(File dir, int numTabs) { File entry = dir.openNextFile(); if (! entry) { // no more files - //Serial.println("**nomorefiles**"); break; } for (uint8_t i=0; i +/* + Controlling a servo position using a potentiometer (variable resistor) + by Michal Rinott + + modified on 8 Nov 2013 + by Scott Fitzgerald + http://arduino.cc/en/Tutorial/Knob +*/ #include @@ -16,7 +22,7 @@ void setup() void loop() { val = analogRead(potpin); // reads the value of the potentiometer (value between 0 and 1023) - val = map(val, 0, 1023, 0, 179); // scale it to use it with the servo (value between 0 and 180) + val = map(val, 0, 1023, 0, 180); // scale it to use it with the servo (value between 0 and 180) myservo.write(val); // sets the servo position according to the scaled value delay(15); // waits for the servo to get there } diff --git a/libraries/Servo/examples/Sweep/Sweep.ino b/libraries/Servo/examples/Sweep/Sweep.ino index fb326e7e784..0c2e8edca4f 100644 --- a/libraries/Servo/examples/Sweep/Sweep.ino +++ b/libraries/Servo/examples/Sweep/Sweep.ino @@ -1,12 +1,16 @@ -// Sweep -// by BARRAGAN -// This example code is in the public domain. +/* Sweep + by BARRAGAN + This example code is in the public domain. + modified 8 Nov 2013 + by Scott Fitzgerald + http://arduino.cc/en/Tutorial/Sweep +*/ #include Servo myservo; // create servo object to control a servo - // a maximum of eight servo objects can be created + // twelve servo objects can be created on most boards int pos = 0; // variable to store the servo position @@ -15,15 +19,14 @@ void setup() myservo.attach(9); // attaches the servo on pin 9 to the servo object } - void loop() { - for(pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees + for(pos = 0; pos <= 180; pos += 1) // goes from 0 degrees to 180 degrees { // in steps of 1 degree myservo.write(pos); // tell servo to go to position in variable 'pos' delay(15); // waits 15ms for the servo to reach the position } - for(pos = 180; pos>=1; pos-=1) // goes from 180 degrees to 0 degrees + for(pos = 180; pos>=0; pos-=1) // goes from 180 degrees to 0 degrees { myservo.write(pos); // tell servo to go to position in variable 'pos' delay(15); // waits 15ms for the servo to reach the position diff --git a/libraries/SoftwareSerial/SoftwareSerial.cpp b/libraries/SoftwareSerial/SoftwareSerial.cpp index 64496febb25..d1f6c9256a6 100755 --- a/libraries/SoftwareSerial/SoftwareSerial.cpp +++ b/libraries/SoftwareSerial/SoftwareSerial.cpp @@ -355,7 +355,7 @@ SoftwareSerial::~SoftwareSerial() void SoftwareSerial::setTX(uint8_t tx) { pinMode(tx, OUTPUT); - digitalWrite(tx, HIGH); + digitalWrite(tx, _inverse_logic ? LOW : HIGH); _transmitBitMask = digitalPinToBitMask(tx); uint8_t port = digitalPinToPort(tx); _transmitPortRegister = portOutputRegister(port); diff --git a/libraries/SoftwareSerial/keywords.txt b/libraries/SoftwareSerial/keywords.txt index 90d4c152d86..aaea17c2022 100755 --- a/libraries/SoftwareSerial/keywords.txt +++ b/libraries/SoftwareSerial/keywords.txt @@ -1,12 +1,13 @@ ####################################### -# Syntax Coloring Map for NewSoftSerial +# Syntax Coloring Map for SoftwareSerial +# (formerly NewSoftSerial) ####################################### ####################################### # Datatypes (KEYWORD1) ####################################### -NewSoftSerial KEYWORD1 +SoftwareSerial KEYWORD1 ####################################### # Methods and Functions (KEYWORD2) @@ -15,11 +16,13 @@ NewSoftSerial KEYWORD1 begin KEYWORD2 end KEYWORD2 read KEYWORD2 +write KEYWORD2 available KEYWORD2 isListening KEYWORD2 overflow KEYWORD2 flush KEYWORD2 listen KEYWORD2 +peek KEYWORD2 ####################################### # Constants (LITERAL1) diff --git a/libraries/TFT/README.md b/libraries/TFT/README.md new file mode 100644 index 00000000000..8489a20d453 --- /dev/null +++ b/libraries/TFT/README.md @@ -0,0 +1,18 @@ +TFT Library +============ + +An Arduino library for the Arduino TFT LCD screen. + +This library enables an Arduino board to communicate with an Arduino TFT LCD screen. It simplifies the process for drawing shapes, lines, images, and text to the screen. +The Arduino TFT library extends the Adafruit GFX, and Adafruit ST7735 libraries that it is based on. The GFX library is responsible for the drawing routines, while the ST7735 library is specific to the screen on the Arduino GTFT. The Arduino specific additions were designed to work as similarly to the Processing API as possible. + +Onboard the screen is a SD card slot, which can be used through the SD library. + +The TFT library relies on the SPI library for communication with the screen and SD card, and needs to be included in all sketches. + +https://github.com/adafruit/Adafruit-GFX-Library +https://github.com/adafruit/Adafruit-ST7735-Library +http://arduino.cc/en/Reference/SD +http://arduino.cc/en/Reference/SPI + +http://arduino.cc/en/Reference/TFTLibrary \ No newline at end of file diff --git a/libraries/TFT/TFT.cpp b/libraries/TFT/TFT.cpp new file mode 100644 index 00000000000..57f71f219cb --- /dev/null +++ b/libraries/TFT/TFT.cpp @@ -0,0 +1,19 @@ +#include "TFT.h" + +#if (USB_VID == 0x2341) && (USB_PID == 0x803C) // are we building for Esplora? +TFT EsploraTFT(7, 0, 1); +#endif + +TFT::TFT(uint8_t CS, uint8_t RS, uint8_t RST) + : Adafruit_ST7735(CS, RS, RST) +{ + // as we already know the orientation (landscape, therefore rotated), + // set default width and height without need to call begin() first. + _width = ST7735_TFTHEIGHT; + _height = ST7735_TFTWIDTH; +} + +void TFT::begin() { + initR(INITR_REDTAB); + setRotation(1); +} diff --git a/libraries/TFT/TFT.h b/libraries/TFT/TFT.h new file mode 100644 index 00000000000..06b6ac3c77b --- /dev/null +++ b/libraries/TFT/TFT.h @@ -0,0 +1,28 @@ + +#ifndef _ARDUINO_TFT_H +#define _ARDUINO_TFT_H + +#include "Arduino.h" +#include "utility/Adafruit_GFX.h" +#include "utility/Adafruit_ST7735.h" + +/// The Arduino LCD is a ST7735-based device. +/// By default, it is mounted horizontally. +/// TFT class follows the convention of other +/// Arduino library classes by adding a begin() method +/// to be called in the setup() routine. +/// @author Enrico Gueli +class TFT : public Adafruit_ST7735 { +public: + TFT(uint8_t CS, uint8_t RS, uint8_t RST); + + void begin(); +}; + +/// Esplora boards have hard-wired connections with +/// the Arduino LCD if mounted on the onboard connector. +#if (USB_VID == 0x2341) && (USB_PID == 0x803C) // are we building for Esplora? +extern TFT EsploraTFT; +#endif + +#endif // _ARDUINO_TFT_H diff --git a/libraries/TFT/examples/Arduino/TFTBitmapLogo/TFTBitmapLogo.ino b/libraries/TFT/examples/Arduino/TFTBitmapLogo/TFTBitmapLogo.ino new file mode 100644 index 00000000000..da7a94d4111 --- /dev/null +++ b/libraries/TFT/examples/Arduino/TFTBitmapLogo/TFTBitmapLogo.ino @@ -0,0 +1,108 @@ +/* + + Arduino TFT Bitmap Logo example + + This example reads an image file from a micro-SD card + and draws it on the screen, at random locations. + + In this sketch, the Arduino logo is read from a micro-SD card. + There is a .bmp file included with this sketch. + - open the sketch folder (Ctrl-K or Cmd-K) + - copy the "arduino.bmp" file to a micro-SD + - put the SD into the SD slot of the Arduino TFT module. + + This example code is in the public domain. + + Created 19 April 2013 by Enrico Gueli + + http://arduino.cc/en/Tutorial/TFTBitmapLogo + + */ + +// include the necessary libraries +#include +#include +#include // Arduino LCD library + +// pin definition for the Uno +#define sd_cs 4 +#define lcd_cs 10 +#define dc 9 +#define rst 8 + +// pin definition for the Leonardo +//#define sd_cs 8 +//#define lcd_cs 7 +//#define dc 0 +//#define rst 1 + +TFT TFTscreen = TFT(lcd_cs, dc, rst); + +// this variable represents the image to be drawn on screen +PImage logo; + + +void setup() { + // initialize the GLCD and show a message + // asking the user to open the serial line + TFTscreen.begin(); + TFTscreen.background(255, 255, 255); + + TFTscreen.stroke(0, 0, 255); + TFTscreen.println(); + TFTscreen.println("Arduino TFT Bitmap Example"); + TFTscreen.stroke(0, 0, 0); + TFTscreen.println("Open serial monitor"); + TFTscreen.println("to run the sketch"); + + // initialize the serial port: it will be used to + // print some diagnostic info + Serial.begin(9600); + while (!Serial) { + // wait for serial line to be ready + } + + // clear the GLCD screen before starting + TFTscreen.background(255, 255, 255); + + // try to access the SD card. If that fails (e.g. + // no card present), the setup process will stop. + Serial.print("Initializing SD card..."); + if (!SD.begin(sd_cs)) { + Serial.println("failed!"); + return; + } + Serial.println("OK!"); + + // initialize and clear the GLCD screen + TFTscreen.begin(); + TFTscreen.background(255, 255, 255); + + // now that the SD card can be access, try to load the + // image file. + logo = TFTscreen.loadImage("arduino.bmp"); + if (!logo.isValid()) { + Serial.println("error while loading arduino.bmp"); + } +} + +void loop() { + // don't do anything if the image wasn't loaded correctly. + if (logo.isValid() == false) { + return; + } + + Serial.println("drawing image"); + + // get a random location where to draw the image. + // To avoid the image to be draw outside the screen, + // take into account the image size. + int x = random(TFTscreen.width() - logo.width()); + int y = random(TFTscreen.height() - logo.height()); + + // draw the image to the screen + TFTscreen.image(logo, x, y); + + // wait a little bit before drawing again + delay(1500); +} diff --git a/libraries/TFT/examples/Arduino/TFTBitmapLogo/arduino.bmp b/libraries/TFT/examples/Arduino/TFTBitmapLogo/arduino.bmp new file mode 100644 index 00000000000..09c670ab54f Binary files /dev/null and b/libraries/TFT/examples/Arduino/TFTBitmapLogo/arduino.bmp differ diff --git a/libraries/TFT/examples/Arduino/TFTColorPicker/TFTColorPicker.ino b/libraries/TFT/examples/Arduino/TFTColorPicker/TFTColorPicker.ino new file mode 100644 index 00000000000..74fc1763145 --- /dev/null +++ b/libraries/TFT/examples/Arduino/TFTColorPicker/TFTColorPicker.ino @@ -0,0 +1,67 @@ +/* + + TFT Color Picker + + This example for the Arduino screen reads the input of + potentiometers or analog sensors attached to A0, A1, + and A2 and uses the values to change the screen's color. + + This example code is in the public domain. + + Created 15 April 2013 by Scott Fitzgerald + + http://arduino.cc/en/Tutorial/TFTColorPicker + + */ + +// pin definition for the Uno +#define cs 10 +#define dc 9 +#define rst 8 + +// pin definition for the Leonardo +// #define cs 7 +// #define dc 0 +// #define rst 1 + +#include // Arduino LCD library +#include + +TFT TFTscreen = TFT(cs, dc, rst); + +void setup() { + // begin serial communication + Serial.begin(9600); + + // initialize the display + TFTscreen.begin(); + + // set the background to white + TFTscreen.background(255, 255, 255); + +} + +void loop() { + + // read the values from your sensors and scale them to 0-255 + int redVal = map(analogRead(A0), 0, 1023, 0, 255); + int greenVal = map(analogRead(A1), 0, 1023, 0, 255); + int blueVal = map(analogRead(A2), 0, 1023, 0, 255); + + // draw the background based on the mapped values + TFTscreen.background(redVal, greenVal, blueVal); + + // send the values to the serial monitor + Serial.print("background("); + Serial.print(redVal); + Serial.print(" , "); + Serial.print(greenVal); + Serial.print(" , "); + Serial.print(blueVal); + Serial.println(")"); + + // wait for a moment + delay(33); + +} + diff --git a/libraries/TFT/examples/Arduino/TFTDisplayText/TFTDisplayText.ino b/libraries/TFT/examples/Arduino/TFTDisplayText/TFTDisplayText.ino new file mode 100644 index 00000000000..f482bd1cfc8 --- /dev/null +++ b/libraries/TFT/examples/Arduino/TFTDisplayText/TFTDisplayText.ino @@ -0,0 +1,74 @@ +/* + Arduino TFT text example + + This example demonstrates how to draw text on the + TFT with an Arduino. The Arduino reads the value + of an analog sensor attached to pin A0, and writes + the value to the LCD screen, updating every + quarter second. + + This example code is in the public domain + + Created 15 April 2013 by Scott Fitzgerald + + http://arduino.cc/en/Tutorial/TFTDisplayText + + */ + +#include // Arduino LCD library +#include + +// pin definition for the Uno +#define cs 10 +#define dc 9 +#define rst 8 + +// pin definition for the Leonardo +// #define cs 7 +// #define dc 0 +// #define rst 1 + +// create an instance of the library +TFT TFTscreen = TFT(cs, dc, rst); + +// char array to print to the screen +char sensorPrintout[4]; + +void setup() { + + // Put this line at the beginning of every sketch that uses the GLCD: + TFTscreen.begin(); + + // clear the screen with a black background + TFTscreen.background(0, 0, 0); + + // write the static text to the screen + // set the font color to white + TFTscreen.stroke(255,255,255); + // set the font size + TFTscreen.setTextSize(2); + // write the text to the top left corner of the screen + TFTscreen.text("Sensor Value :\n ",0,0); + // ste the font size very large for the loop + TFTscreen.setTextSize(5); +} + +void loop() { + + // Read the value of the sensor on A0 + String sensorVal = String(analogRead(A0)); + + // convert the reading to a char array + sensorVal.toCharArray(sensorPrintout, 4); + + // set the font color + TFTscreen.stroke(255,255,255); + // print the sensor value + TFTscreen.text(sensorPrintout, 0, 20); + // wait for a moment + delay(250); + // erase the text you just wrote + TFTscreen.stroke(0,0,0); + TFTscreen.text(sensorPrintout, 0, 20); +} + diff --git a/libraries/TFT/examples/Arduino/TFTEtchASketch/TFTEtchASketch.ino b/libraries/TFT/examples/Arduino/TFTEtchASketch/TFTEtchASketch.ino new file mode 100644 index 00000000000..29e3483b6f6 --- /dev/null +++ b/libraries/TFT/examples/Arduino/TFTEtchASketch/TFTEtchASketch.ino @@ -0,0 +1,84 @@ +/* + + TFT EtchASketch + + This example for the Arduino screen draws a white point + on the GLCD based on the values of 2 potentiometers. + To clear the screen, press a button attached to pin 2. + + This example code is in the public domain. + + Created 15 April 2013 by Scott Fitzgerald + + http://arduino.cc/en/Tutorial/TFTEtchASketch + + */ + +#include // Arduino LCD library +#include + +// pin definition for the Uno +#define cs 10 +#define dc 9 +#define rst 8 + +// pin definition for the Leonardo +// #define cs 7 +// #define dc 0 +// #define rst 1 + +TFT TFTscreen = TFT(cs, dc, rst); + +// initial position of the cursor +int xPos = TFTscreen.width()/2; +int yPos = TFTscreen.height()/2; + +// pin the erase switch is connected to +int erasePin = 2; + +void setup() { + // declare inputs + pinMode(erasePin, INPUT); + // initialize the screen + TFTscreen.begin(); + // make the background black + TFTscreen.background(0,0,0); +} + +void loop() +{ + // read the potentiometers on A0 and A1 + int xValue = analogRead(A0); + int yValue = analogRead(A1); + + // map the values and update the position + xPos = xPos + (map(xValue, 0, 1023, 2, -2)); + yPos = yPos + (map(yValue, 0, 1023, -2, 2)); + +// don't let the point go past the screen edges + if(xPos > 159){ + (xPos = 159); + } + + if(xPos < 0){ + (xPos = 0); + } + if(yPos > 127){ + (yPos = 127); + } + + if(yPos < 0){ + (yPos = 0); + } + + // draw the point + TFTscreen.stroke(255,255,255); + TFTscreen.point(xPos,yPos); + + // read the value of the pin, and erase the screen if pressed + if(digitalRead(erasePin) == HIGH){ + TFTscreen.background(0,0,0); + } + + delay(33); +} diff --git a/libraries/TFT/examples/Arduino/TFTGraph/TFTGraph.ino b/libraries/TFT/examples/Arduino/TFTGraph/TFTGraph.ino new file mode 100644 index 00000000000..39ae49b93ae --- /dev/null +++ b/libraries/TFT/examples/Arduino/TFTGraph/TFTGraph.ino @@ -0,0 +1,71 @@ +/* + + TFT Graph + + This example for an Arduino screen reads + the value of an analog sensor on A0, and + graphs the values on the screen. + + This example code is in the public domain. + + Created 15 April 2013 by Scott Fitzgerald + + http://arduino.cc/en/Tutorial/TFTGraph + + */ + +#include // Arduino LCD library +#include + + // pin definition for the Uno +#define cs 10 +#define dc 9 +#define rst 8 + +// pin definition for the Leonardo +// #define cs 7 +// #define dc 0 +// #define rst 1 + +TFT TFTscreen = TFT(cs, dc, rst); + +// position of the line on screen +int xPos = 0; + +void setup(){ + // initialize the serial port + Serial.begin(9600); + + // initialize the display + TFTscreen.begin(); + + // clear the screen with a pretty color + TFTscreen.background(250,16,200); +} + +void loop(){ + // read the sensor and map it to the screen height + int sensor = analogRead(A0); + int drawHeight = map(sensor,0,1023,0,TFTscreen.height()); + + // print out the height to the serial monitor + Serial.println(drawHeight); + + // draw a line in a nice color + TFTscreen.stroke(250,180,10); + TFTscreen.line(xPos, TFTscreen.height()-drawHeight, xPos, TFTscreen.height()); + + // if the graph has reached the screen edge + // erase the screen and start again + if (xPos >= 160) { + xPos = 0; + TFTscreen.background(250,16,200); + } + else { + // increment the horizontal position: + xPos++; + } + + delay(16); +} + diff --git a/libraries/TFT/examples/Arduino/TFTPong/TFTPong.ino b/libraries/TFT/examples/Arduino/TFTPong/TFTPong.ino new file mode 100644 index 00000000000..02ea11c4fe4 --- /dev/null +++ b/libraries/TFT/examples/Arduino/TFTPong/TFTPong.ino @@ -0,0 +1,135 @@ +/* + + TFT Pong + + This example for the Arduino screen reads the values + of 2 potentiometers to move a rectangular platform + on the x and y axes. The platform can intersect + with a ball causing it to bounce. + + This example code is in the public domain. + + Created by Tom Igoe December 2012 + Modified 15 April 2013 by Scott Fitzgerald + + http://arduino.cc/en/Tutorial/TFTPong + + */ + +#include // Arduino LCD library +#include + +// pin definition for the Uno +#define cs 10 +#define dc 9 +#define rst 8 + +// pin definition for the Leonardo +// #define cs 7 +// #define dc 0 +// #define rst 1 + +TFT TFTscreen = TFT(cs, dc, rst); + +// variables for the position of the ball and paddle +int paddleX = 0; +int paddleY = 0; +int oldPaddleX, oldPaddleY; +int ballDirectionX = 1; +int ballDirectionY = 1; + +int ballSpeed = 10; // lower numbers are faster + +int ballX, ballY, oldBallX, oldBallY; + +void setup() { + // initialize the display + TFTscreen.begin(); + // black background + TFTscreen.background(0,0,0); +} + +void loop() { + + // save the width and height of the screen + int myWidth = TFTscreen.width(); + int myHeight = TFTscreen.height(); + + // map the paddle's location to the position of the potentiometers + paddleX = map(analogRead(A0), 512, -512, 0, myWidth) - 20/2; + paddleY = map(analogRead(A1), 512, -512, 0, myHeight) - 5/2; + + // set the fill color to black and erase the previous + // position of the paddle if different from present + TFTscreen.fill(0,0,0); + + if (oldPaddleX != paddleX || oldPaddleY != paddleY) { + TFTscreen.rect(oldPaddleX, oldPaddleY, 20, 5); + } + + // draw the paddle on screen, save the current position + // as the previous. + TFTscreen.fill(255,255,255); + + TFTscreen.rect(paddleX, paddleY, 20, 5); + oldPaddleX = paddleX; + oldPaddleY = paddleY; + + // update the ball's position and draw it on screen + if (millis() % ballSpeed < 2) { + moveBall(); + } +} + +// this function determines the ball's position on screen +void moveBall() { + // if the ball goes offscreen, reverse the direction: + if (ballX > TFTscreen.width() || ballX < 0) { + ballDirectionX = -ballDirectionX; + } + + if (ballY > TFTscreen.height() || ballY < 0) { + ballDirectionY = -ballDirectionY; + } + + // check if the ball and the paddle occupy the same space on screen + if (inPaddle(ballX, ballY, paddleX, paddleY, 20, 5)) { + ballDirectionX = -ballDirectionX; + ballDirectionY = -ballDirectionY; + } + + // update the ball's position + ballX += ballDirectionX; + ballY += ballDirectionY; + +// erase the ball's previous position + TFTscreen.fill(0,0,0); + + if (oldBallX != ballX || oldBallY != ballY) { + TFTscreen.rect(oldBallX, oldBallY, 5, 5); + } + + + // draw the ball's current position + TFTscreen.fill(255,255,255); + TFTscreen.rect(ballX, ballY, 5, 5); + + oldBallX = ballX; + oldBallY = ballY; + +} + +// this function checks the position of the ball +// to see if it intersects with the paddle +boolean inPaddle(int x, int y, int rectX, int rectY, int rectWidth, int rectHeight) { + boolean result = false; + + if ((x >= rectX && x <= (rectX + rectWidth)) && + (y >= rectY && y <= (rectY + rectHeight))) { + result = true; + } + +return result; +} + + diff --git a/libraries/TFT/examples/Esplora/EsploraTFTBitmapLogo/EsploraTFTBitmapLogo.ino b/libraries/TFT/examples/Esplora/EsploraTFTBitmapLogo/EsploraTFTBitmapLogo.ino new file mode 100644 index 00000000000..3d3f230ced3 --- /dev/null +++ b/libraries/TFT/examples/Esplora/EsploraTFTBitmapLogo/EsploraTFTBitmapLogo.ino @@ -0,0 +1,101 @@ +/* + + Esplora TFT Bitmap Logos + + This example for the Arduino TFT screen is for use + with an Arduino Esplora. + + This example reads an image file from a micro-SD card + and draws it on the screen, at random locations. + + There is a .bmp file included with this sketch. + - open the sketch folder (Ctrl-K or Cmd-K) + - copy the "arduino.bmp" file to a micro-SD + - put the SD into the SD slot of the Arduino LCD module. + + This example code is in the public domain. + + Created 19 April 2013 by Enrico Gueli + + http://arduino.cc/en/Tutorial/EsploraTFTBitmapLogo + + */ + +// include the necessary libraries +#include +#include +#include +#include // Arduino LCD library + +// the Esplora pin connected to the chip select line for SD card +#define SD_CS 8 + +// this variable represents the image to be drawn on screen +PImage logo; + +void setup() { + // initialize the GLCD and show a message + // asking the user to open the serial line + EsploraTFT.begin(); + EsploraTFT.background(255, 255, 255); + + EsploraTFT.stroke(0, 0, 255); + EsploraTFT.println(); + EsploraTFT.println("Arduino LCD Bitmap Example"); + EsploraTFT.stroke(0, 0, 0); + EsploraTFT.println("Open serial monitor"); + EsploraTFT.println("to run the sketch"); + + // initialize the serial port: it will be used to + // print some diagnostic info + Serial.begin(9600); + while (!Serial) { + // wait for serial monitor to be open + } + + // try to access the SD card. If that fails (e.g. + // no card present), the Esplora's LED will turn red. + Serial.print("Initializing SD card..."); + if (!SD.begin(SD_CS)) { + Serial.println("failed!"); + Esplora.writeRed(255); + return; + } + Serial.println("OK!"); + + // clear the GLCD screen before starting + EsploraTFT.background(255, 255, 255); + + // now that the SD card can be access, try to load the + // image file. The Esplora LED will turn green or red if + // the loading went OK or not. + Esplora.writeRGB(0, 0, 0); + logo = EsploraTFT.loadImage("arduino.bmp"); + if (logo.isValid()) { + Esplora.writeGreen(255); + } + else + Esplora.writeRed(255); + +} + +void loop() { + // don't do anything if the image wasn't loaded correctly. + if (logo.isValid() == false) { + return; + } + + Serial.println("drawing image"); + + // get a random location where to draw the image. + // To avoid the image to be draw outside the screen, + // take into account the image size. + int x = random(EsploraTFT.width() - logo.width()); + int y = random(EsploraTFT.height() - logo.height()); + + // draw the image to the screen + EsploraTFT.image(logo, x, y); + + // wait a little bit before drawing again + delay(1500); +} diff --git a/libraries/TFT/examples/Esplora/EsploraTFTBitmapLogo/arduino.bmp b/libraries/TFT/examples/Esplora/EsploraTFTBitmapLogo/arduino.bmp new file mode 100644 index 00000000000..09c670ab54f Binary files /dev/null and b/libraries/TFT/examples/Esplora/EsploraTFTBitmapLogo/arduino.bmp differ diff --git a/libraries/TFT/examples/Esplora/EsploraTFTColorPicker/EsploraTFTColorPicker.ino b/libraries/TFT/examples/Esplora/EsploraTFTColorPicker/EsploraTFTColorPicker.ino new file mode 100644 index 00000000000..63a0ee216d0 --- /dev/null +++ b/libraries/TFT/examples/Esplora/EsploraTFTColorPicker/EsploraTFTColorPicker.ino @@ -0,0 +1,54 @@ +/* + + Esplora TFT Color Picker + + This example for the Esplora with an Arduino TFT reads + the input of the joystick and slider, using the values + to change the screen's color. + + This example code is in the public domain. + + Created 15 April 2013 by Scott Fitzgerald + + http://arduino.cc/en/Tutorial/TFTColorPicker + + */ + +#include +#include // Arduino LCD library +#include + +void setup() { + Serial.begin(9600); + + // initialize the LCD + EsploraTFT.begin(); + + // start out with a white screen + EsploraTFT.background(255, 255, 255); + +} + +void loop() { + + // map the values from sensors + int xValue = map(Esplora.readJoystickX(), -512, 512, 0, 255); // read the joystick's X position + int yValue = map(Esplora.readJoystickY(), -512, 512, 0, 255); // read the joystick's Y position + int slider = map(Esplora.readSlider(), 0, 1023, 0, 255); // read the slider's position + + // change the background color based on the mapped values + EsploraTFT.background(xValue, yValue, slider); + + // print the mapped values to the Serial monitor + Serial.print("background("); + Serial.print(xValue); + Serial.print(" , "); + Serial.print(yValue); + Serial.print(" , "); + Serial.print(slider); + Serial.println(")"); + + delay(33); + +} + diff --git a/libraries/TFT/examples/Esplora/EsploraTFTEtchASketch/EsploraTFTEtchASketch.ino b/libraries/TFT/examples/Esplora/EsploraTFTEtchASketch/EsploraTFTEtchASketch.ino new file mode 100644 index 00000000000..a1430d301dd --- /dev/null +++ b/libraries/TFT/examples/Esplora/EsploraTFTEtchASketch/EsploraTFTEtchASketch.ino @@ -0,0 +1,83 @@ +/* + + Esplora TFT EtchASketch + + This example for the Arduino TFT and Esplora draws + a white line on the screen, based on the position + of the joystick. To clear the screen, shake the + Esplora, using the values from the accelerometer. + + This example code is in the public domain. + + Created 15 April 2013 by Scott Fitzgerald + + http://arduino.cc/en/Tutorial/EsploraTFTEtchASketch + + */ + +#include +#include // Arduino LCD library +#include + +// initial position of the cursor +int xPos = EsploraTFT.width()/2; +int yPos = EsploraTFT.height()/2; + +void setup() { + // initialize the display + EsploraTFT.begin(); + + // clear the background + EsploraTFT.background(0,0,0); +} + +void loop() +{ + + int xAxis = Esplora.readJoystickX(); // read the X axis + int yAxis = Esplora.readJoystickY(); // read the Y axis + + // update the position of the line + // depending on the position of the joystick + if (xAxis<10 && xAxis>-10){ + xPos=xPos; + } + else{ + xPos = xPos + (map(xAxis, -512, 512, 2, -2)); + } + if (yAxis<10 && yAxis>-10){ + yAxis=yAxis; + } + else{ + yPos = yPos + (map(yAxis, -512, 512, -2, 2)); + } + +// don't let the point go past the screen edges + if(xPos > 159){ + (xPos = 159); + } + + if(xPos < 0){ + (xPos = 0); + } + if(yPos > 127){ + (yPos = 127); + } + + if(yPos < 0){ + (yPos = 0); + } + + // draw the point + EsploraTFT.stroke(255,255,255); + EsploraTFT.point(xPos,yPos); + + // check the accelerometer values and clear + // the screen if it is being shaken + if(abs(Esplora.readAccelerometer(X_AXIS))>200 || abs(Esplora.readAccelerometer(Y_AXIS))>200){ + EsploraTFT.background(0,0,0); + } + + delay(33); +} + diff --git a/libraries/TFT/examples/Esplora/EsploraTFTGraph/EsploraTFTGraph.ino b/libraries/TFT/examples/Esplora/EsploraTFTGraph/EsploraTFTGraph.ino new file mode 100644 index 00000000000..7f2a4276171 --- /dev/null +++ b/libraries/TFT/examples/Esplora/EsploraTFTGraph/EsploraTFTGraph.ino @@ -0,0 +1,56 @@ +/* + + Esplora TFT Graph + + This example for the Esplora with an Arduino TFT reads + the value of the light sensor, and graphs the values on + the screen. + + This example code is in the public domain. + + Created 15 April 2013 by Scott Fitzgerald + + http://arduino.cc/en/Tutorial/EsploraTFTGraph + + */ + +#include +#include // Arduino LCD library +#include + +// position of the line on screen +int xPos = 0; + +void setup(){ + + // initialize the screen + EsploraTFT.begin(); + + // clear the screen with a nice color + EsploraTFT.background(250,16,200); +} + +void loop(){ + + // read the sensor value + int sensor = Esplora.readLightSensor(); + // map the sensor value to the height of the screen + int graphHeight = map(sensor,0,1023,0,EsploraTFT.height()); + + // draw the line in a pretty color + EsploraTFT.stroke(250,180,10); + EsploraTFT.line(xPos, EsploraTFT.height() - graphHeight, xPos, EsploraTFT.height()); + + // if the graph reaches the edge of the screen + // erase it and start over from the other side + if (xPos >= 160) { + xPos = 0; + EsploraTFT.background(250,16,200); + } + else { + // increment the horizontal position: + xPos++; + } + + delay(16); +} diff --git a/libraries/TFT/examples/Esplora/EsploraTFTHorizon/EsploraTFTHorizon.ino b/libraries/TFT/examples/Esplora/EsploraTFTHorizon/EsploraTFTHorizon.ino new file mode 100644 index 00000000000..a7945c9314f --- /dev/null +++ b/libraries/TFT/examples/Esplora/EsploraTFTHorizon/EsploraTFTHorizon.ino @@ -0,0 +1,63 @@ +/* + + Esplora TFT Horizon + + This example for the Arduino TFT and Esplora draws + a line on the screen that stays level with the ground + as you tile the Esplora side to side + + This example code is in the public domain. + + Created 15 April 2013 by Scott Fitzgerald + + http://arduino.cc/en/Tutorial/EsploraTFTHorizon + + */ + +#include +#include // Arduino LCD library +#include + +// horizontal start and end positions +int yStart = EsploraTFT.height()/2; +int yEnd = EsploraTFT.height()/2; + +// previous start and end positions +int oldEndY; +int oldStartY; + +void setup() { + // initialize the display + EsploraTFT.begin(); + // make the background black + EsploraTFT.background(0,0,0); +} + +void loop() +{ + // read the x-axis of te accelerometer + int tilt = Esplora.readAccelerometer(X_AXIS); + + // the values are 100 when tilted to the left + // and -100 when tilted to the right + // map these values to the start and end points + yStart = map(tilt,-100,100,EsploraTFT.height(),0); + yEnd = map(tilt,-100,100,0,EsploraTFT.height()); + + // if the previous values are different than the current values + // erase the previous line + if (oldStartY != yStart || oldEndY != yEnd) { + EsploraTFT.stroke(0,0,0); + EsploraTFT.line(0, oldStartY, EsploraTFT.width(), oldEndY); + } + + // draw the line in magenta + EsploraTFT.stroke(255,0,255); + EsploraTFT.line(0,yStart,EsploraTFT.width(),yEnd); + + // save the current start and end points + // to compare int he next loop + oldStartY= yStart; + oldEndY = yEnd; + delay(10); +} diff --git a/libraries/TFT/examples/Esplora/EsploraTFTPong/EsploraTFTPong.ino b/libraries/TFT/examples/Esplora/EsploraTFTPong/EsploraTFTPong.ino new file mode 100644 index 00000000000..e3422d48d4a --- /dev/null +++ b/libraries/TFT/examples/Esplora/EsploraTFTPong/EsploraTFTPong.ino @@ -0,0 +1,126 @@ +/* + + Esplora TFT Pong + + This example for the Esplora with an Arduino TFT screen reads + the value of the joystick to move a rectangular platform + on the x and y axes. The platform can intersect with a ball + causing it to bounce. The Esplora's slider adjusts the speed + of the ball. + + This example code is in the public domain. + + Created by Tom Igoe December 2012 + Modified 15 April 2013 by Scott Fitzgerald + + http://arduino.cc/en/Tutorial/EsploraTFTPong + + */ + +#include +#include // Arduino LCD library +#include + +// variables for the position of the ball and paddle +int paddleX = 0; +int paddleY = 0; +int oldPaddleX, oldPaddleY; +int ballDirectionX = 1; +int ballDirectionY = 1; + +int ballX, ballY, oldBallX, oldBallY; + +void setup() { + + Serial.begin(9600); + + // initialize the display + EsploraTFT.begin(); + // set the background the black + EsploraTFT.background(0,0,0); +} + +void loop() { + // save the width and height of the screen + int myWidth = EsploraTFT.width(); + int myHeight = EsploraTFT.height(); + + // map the paddle's location to the joystick's position + paddleX = map(Esplora.readJoystickX(), 512, -512, 0, myWidth) - 20/2; + paddleY = map(Esplora.readJoystickY(), -512, 512, 0, myHeight) - 5/2; + Serial.print(paddleX); + Serial.print(" "); + Serial.println(paddleY); + + // set the fill color to black and erase the previous + // position of the paddle if different from present + EsploraTFT.fill(0,0,0); + + if (oldPaddleX != paddleX || oldPaddleY != paddleY) { + EsploraTFT.rect(oldPaddleX, oldPaddleY, 20, 5); + } + + // draw the paddle on screen, save the current position + // as the previous. + EsploraTFT.fill(255,255,255); + EsploraTFT.rect(paddleX, paddleY, 20, 5); + oldPaddleX = paddleX; + oldPaddleY = paddleY; + + // read the slider to determinde the speed of the ball + int ballSpeed = map(Esplora.readSlider(), 0, 1023, 0, 80)+1; + if (millis() % ballSpeed < 2) { + moveBall(); + } +} + + +// this function determines the ball's position on screen +void moveBall() { + // if the ball goes offscreen, reverse the direction: + if (ballX > EsploraTFT.width() || ballX < 0) { + ballDirectionX = -ballDirectionX; + } + + if (ballY > EsploraTFT.height() || ballY < 0) { + ballDirectionY = -ballDirectionY; + } + + // check if the ball and the paddle occupy the same space on screen + if (inPaddle(ballX, ballY, paddleX, paddleY, 20, 5)) { + ballDirectionY = -ballDirectionY; + } + + // update the ball's position + ballX += ballDirectionX; + ballY += ballDirectionY; + + // erase the ball's previous position + EsploraTFT.fill(0,0,0); + + if (oldBallX != ballX || oldBallY != ballY) { + EsploraTFT.rect(oldBallX, oldBallY, 5, 5); + } + + // draw the ball's current position + EsploraTFT.fill(255,255,255); + + EsploraTFT.rect(ballX, ballY, 5, 5); + + oldBallX = ballX; + oldBallY = ballY; + +} + +// this function checks the position of the ball +// to see if it intersects with the paddle +boolean inPaddle(int x, int y, int rectX, int rectY, int rectWidth, int rectHeight) { + boolean result = false; + + if ((x >= rectX && x <= (rectX + rectWidth)) && + (y >= rectY && y <= (rectY + rectHeight))) { + result = true; + } + + return result; +} diff --git a/libraries/TFT/examples/Esplora/EsploraTFTTemp/EsploraTFTTemp.ino b/libraries/TFT/examples/Esplora/EsploraTFTTemp/EsploraTFTTemp.ino new file mode 100644 index 00000000000..b475d2da755 --- /dev/null +++ b/libraries/TFT/examples/Esplora/EsploraTFTTemp/EsploraTFTTemp.ino @@ -0,0 +1,64 @@ +/* + + Esplora TFT Temperature Display + + This example for the Arduino TFT screen is for use + with an Arduino Esplora. + + This example reads the temperature of the Esplora's + on board thermisistor and displays it on an attached + LCD screen, updating every second. + + This example code is in the public domain. + + Created 15 April 2013 by Scott Fitzgerald + + http://arduino.cc/en/Tutorial/EsploraTFTTemp + + */ + +// include the necessary libraries +#include +#include // Arduino LCD library +#include + +char tempPrintout[3]; // array to hold the temperature data + +void setup() { + + // Put this line at the beginning of every sketch that uses the GLCD + EsploraTFT.begin(); + + // clear the screen with a black background + EsploraTFT.background(0,0,0); + + // set the text color to magenta + EsploraTFT.stroke(200,20,180); + // set the text to size 2 + EsploraTFT.setTextSize(2); + // start the text at the top left of the screen + // this text is going to remain static + EsploraTFT.text("Degrees in C :\n ",0,0); + + // set the text in the loop to size 5 + EsploraTFT.setTextSize(5); +} + +void loop() { + + // read the temperature in Celcius and store it in a String + String temperature = String(Esplora.readTemperature(DEGREES_C)); + + // convert the string to a char array + temperature.toCharArray(tempPrintout, 3); + + // set the text color to white + EsploraTFT.stroke(255,255,255); + // print the temperature one line below the static text + EsploraTFT.text(tempPrintout, 0, 30); + + delay(1000); + // erase the text for the next loop + EsploraTFT.stroke(0,0,0); + EsploraTFT.text(tempPrintout, 0, 30); +} diff --git a/libraries/TFT/keywords.txt b/libraries/TFT/keywords.txt new file mode 100644 index 00000000000..0ddb3b53612 --- /dev/null +++ b/libraries/TFT/keywords.txt @@ -0,0 +1,20 @@ +####################################### +# Syntax Coloring Map For Arduino GLCD +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +TFT KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + + +####################################### +# Constants (LITERAL1) +####################################### + +EsploraTFT LITERAL1 diff --git a/libraries/TFT/utility/Adafruit-README.txt b/libraries/TFT/utility/Adafruit-README.txt new file mode 100644 index 00000000000..6f3b682df67 --- /dev/null +++ b/libraries/TFT/utility/Adafruit-README.txt @@ -0,0 +1,21 @@ +This is a library for the Adafruit 1.8" SPI display. +This library works with the Adafruit 1.8" TFT Breakout w/SD card + ----> http://www.adafruit.com/products/358 +as well as Adafruit raw 1.8" TFT display + ----> http://www.adafruit.com/products/618 + +Check out the links above for our tutorials and wiring diagrams. +These displays use SPI to communicate, 4 or 5 pins are required +to interface (RST is optional). +Adafruit invests time and resources providing this open source code, +please support Adafruit and open-source hardware by purchasing +products from Adafruit! + +Written by Limor Fried/Ladyada for Adafruit Industries. +MIT license, all text above must be included in any redistribution + +To download. click the DOWNLOADS button in the top right corner, rename the uncompressed folder Adafruit_ST7735. Check that the Adafruit_ST7735 folder contains Adafruit_ST7735.cpp and Adafruit_ST7735. + +Place the Adafruit_ST7735 library folder your /libraries/ folder. You may need to create the libraries subfolder if its your first library. Restart the IDE + +Also requires the Adafruit_GFX library for Arduino. diff --git a/libraries/TFT/utility/Adafruit-license.txt b/libraries/TFT/utility/Adafruit-license.txt new file mode 100644 index 00000000000..4bbfa3948ec --- /dev/null +++ b/libraries/TFT/utility/Adafruit-license.txt @@ -0,0 +1,25 @@ +Software License Agreement (BSD License) + +Copyright (c) 2012, Adafruit Industries. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: +1. Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. +3. Neither the name of the copyright holders nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/libraries/TFT/utility/Adafruit_GFX.cpp b/libraries/TFT/utility/Adafruit_GFX.cpp new file mode 100644 index 00000000000..a7a541cc752 --- /dev/null +++ b/libraries/TFT/utility/Adafruit_GFX.cpp @@ -0,0 +1,671 @@ +/****************************************************************** + This is the core graphics library for all our displays, providing + basic graphics primitives (points, lines, circles, etc.). It needs + to be paired with a hardware-specific library for each display + device we carry (handling the lower-level functions). + + Adafruit invests time and resources providing this open + source code, please support Adafruit and open-source hardware + by purchasing products from Adafruit! + + Written by Limor Fried/Ladyada for Adafruit Industries. + BSD license, check license.txt for more information. + All text above must be included in any redistribution. + ******************************************************************/ + +#include "Adafruit_GFX.h" +#include "glcdfont.c" +#include + +void Adafruit_GFX::constructor(int16_t w, int16_t h) { + _width = WIDTH = w; + _height = HEIGHT = h; + + rotation = 0; + cursor_y = cursor_x = 0; + textsize = 1; + textcolor = textbgcolor = 0xFFFF; + wrap = true; + + strokeColor = 0; + useStroke = true; + fillColor = 0; + useFill = false; + +} + + +// draw a circle outline +void Adafruit_GFX::drawCircle(int16_t x0, int16_t y0, int16_t r, + uint16_t color) { + int16_t f = 1 - r; + int16_t ddF_x = 1; + int16_t ddF_y = -2 * r; + int16_t x = 0; + int16_t y = r; + + drawPixel(x0, y0+r, color); + drawPixel(x0, y0-r, color); + drawPixel(x0+r, y0, color); + drawPixel(x0-r, y0, color); + + while (x= 0) { + y--; + ddF_y += 2; + f += ddF_y; + } + x++; + ddF_x += 2; + f += ddF_x; + + drawPixel(x0 + x, y0 + y, color); + drawPixel(x0 - x, y0 + y, color); + drawPixel(x0 + x, y0 - y, color); + drawPixel(x0 - x, y0 - y, color); + drawPixel(x0 + y, y0 + x, color); + drawPixel(x0 - y, y0 + x, color); + drawPixel(x0 + y, y0 - x, color); + drawPixel(x0 - y, y0 - x, color); + + } +} + +void Adafruit_GFX::drawCircleHelper( int16_t x0, int16_t y0, + int16_t r, uint8_t cornername, uint16_t color) { + int16_t f = 1 - r; + int16_t ddF_x = 1; + int16_t ddF_y = -2 * r; + int16_t x = 0; + int16_t y = r; + + while (x= 0) { + y--; + ddF_y += 2; + f += ddF_y; + } + x++; + ddF_x += 2; + f += ddF_x; + if (cornername & 0x4) { + drawPixel(x0 + x, y0 + y, color); + drawPixel(x0 + y, y0 + x, color); + } + if (cornername & 0x2) { + drawPixel(x0 + x, y0 - y, color); + drawPixel(x0 + y, y0 - x, color); + } + if (cornername & 0x8) { + drawPixel(x0 - y, y0 + x, color); + drawPixel(x0 - x, y0 + y, color); + } + if (cornername & 0x1) { + drawPixel(x0 - y, y0 - x, color); + drawPixel(x0 - x, y0 - y, color); + } + } +} + +void Adafruit_GFX::fillCircle(int16_t x0, int16_t y0, int16_t r, + uint16_t color) { + drawFastVLine(x0, y0-r, 2*r+1, color); + fillCircleHelper(x0, y0, r, 3, 0, color); +} + +// used to do circles and roundrects! +void Adafruit_GFX::fillCircleHelper(int16_t x0, int16_t y0, int16_t r, + uint8_t cornername, int16_t delta, uint16_t color) { + + int16_t f = 1 - r; + int16_t ddF_x = 1; + int16_t ddF_y = -2 * r; + int16_t x = 0; + int16_t y = r; + + while (x= 0) { + y--; + ddF_y += 2; + f += ddF_y; + } + x++; + ddF_x += 2; + f += ddF_x; + + if (cornername & 0x1) { + drawFastVLine(x0+x, y0-y, 2*y+1+delta, color); + drawFastVLine(x0+y, y0-x, 2*x+1+delta, color); + } + if (cornername & 0x2) { + drawFastVLine(x0-x, y0-y, 2*y+1+delta, color); + drawFastVLine(x0-y, y0-x, 2*x+1+delta, color); + } + } +} + +// bresenham's algorithm - thx wikpedia +void Adafruit_GFX::drawLine(int16_t x0, int16_t y0, + int16_t x1, int16_t y1, + uint16_t color) { + int16_t steep = abs(y1 - y0) > abs(x1 - x0); + if (steep) { + swap(x0, y0); + swap(x1, y1); + } + + if (x0 > x1) { + swap(x0, x1); + swap(y0, y1); + } + + int16_t dx, dy; + dx = x1 - x0; + dy = abs(y1 - y0); + + int16_t err = dx / 2; + int16_t ystep; + + if (y0 < y1) { + ystep = 1; + } else { + ystep = -1; + } + + for (; x0<=x1; x0++) { + if (steep) { + drawPixel(y0, x0, color); + } else { + drawPixel(x0, y0, color); + } + err -= dy; + if (err < 0) { + y0 += ystep; + err += dx; + } + } +} + + +// draw a rectangle +void Adafruit_GFX::drawRect(int16_t x, int16_t y, + int16_t w, int16_t h, + uint16_t color) { + drawFastHLine(x, y, w, color); + drawFastHLine(x, y+h-1, w, color); + drawFastVLine(x, y, h, color); + drawFastVLine(x+w-1, y, h, color); +} + +void Adafruit_GFX::drawFastVLine(int16_t x, int16_t y, + int16_t h, uint16_t color) { + // stupidest version - update in subclasses if desired! + drawLine(x, y, x, y+h-1, color); +} + + +void Adafruit_GFX::drawFastHLine(int16_t x, int16_t y, + int16_t w, uint16_t color) { + // stupidest version - update in subclasses if desired! + drawLine(x, y, x+w-1, y, color); +} + +void Adafruit_GFX::fillRect(int16_t x, int16_t y, int16_t w, int16_t h, + uint16_t color) { + // stupidest version - update in subclasses if desired! + for (int16_t i=x; i= y1 >= y0) + if (y0 > y1) { + swap(y0, y1); swap(x0, x1); + } + if (y1 > y2) { + swap(y2, y1); swap(x2, x1); + } + if (y0 > y1) { + swap(y0, y1); swap(x0, x1); + } + + if(y0 == y2) { // Handle awkward all-on-same-line case as its own thing + a = b = x0; + if(x1 < a) a = x1; + else if(x1 > b) b = x1; + if(x2 < a) a = x2; + else if(x2 > b) b = x2; + drawFastHLine(a, y0, b-a+1, color); + return; + } + + int16_t + dx01 = x1 - x0, + dy01 = y1 - y0, + dx02 = x2 - x0, + dy02 = y2 - y0, + dx12 = x2 - x1, + dy12 = y2 - y1, + sa = 0, + sb = 0; + + // For upper part of triangle, find scanline crossings for segments + // 0-1 and 0-2. If y1=y2 (flat-bottomed triangle), the scanline y1 + // is included here (and second loop will be skipped, avoiding a /0 + // error there), otherwise scanline y1 is skipped here and handled + // in the second loop...which also avoids a /0 error here if y0=y1 + // (flat-topped triangle). + if(y1 == y2) last = y1; // Include y1 scanline + else last = y1-1; // Skip it + + for(y=y0; y<=last; y++) { + a = x0 + sa / dy01; + b = x0 + sb / dy02; + sa += dx01; + sb += dx02; + /* longhand: + a = x0 + (x1 - x0) * (y - y0) / (y1 - y0); + b = x0 + (x2 - x0) * (y - y0) / (y2 - y0); + */ + if(a > b) swap(a,b); + drawFastHLine(a, y, b-a+1, color); + } + + // For lower part of triangle, find scanline crossings for segments + // 0-2 and 1-2. This loop is skipped if y1=y2. + sa = dx12 * (y - y1); + sb = dx02 * (y - y0); + for(; y<=y2; y++) { + a = x1 + sa / dy12; + b = x0 + sb / dy02; + sa += dx12; + sb += dx02; + /* longhand: + a = x1 + (x2 - x1) * (y - y1) / (y2 - y1); + b = x0 + (x2 - x0) * (y - y0) / (y2 - y0); + */ + if(a > b) swap(a,b); + drawFastHLine(a, y, b-a+1, color); + } +} + +void Adafruit_GFX::drawBitmap(int16_t x, int16_t y, + const uint8_t *bitmap, int16_t w, int16_t h, + uint16_t color) { + + int16_t i, j, byteWidth = (w + 7) / 8; + + for(j=0; j> (i & 7))) { + drawPixel(x+i, y+j, color); + } + } + } +} + + +#if ARDUINO >= 100 +size_t Adafruit_GFX::write(uint8_t c) { +#else +void Adafruit_GFX::write(uint8_t c) { +#endif + if (c == '\n') { + cursor_y += textsize*8; + cursor_x = 0; + } else if (c == '\r') { + // skip em + } else { + drawChar(cursor_x, cursor_y, c, textcolor, textbgcolor, textsize); + cursor_x += textsize*6; + if (wrap && (cursor_x > (_width - textsize*6))) { + cursor_y += textsize*8; + cursor_x = 0; + } + } +#if ARDUINO >= 100 + return 1; +#endif +} + +// draw a character +void Adafruit_GFX::drawChar(int16_t x, int16_t y, unsigned char c, + uint16_t color, uint16_t bg, uint8_t size) { + + if((x >= _width) || // Clip right + (y >= _height) || // Clip bottom + ((x + 5 * size - 1) < 0) || // Clip left + ((y + 8 * size - 1) < 0)) // Clip top + return; + + for (int8_t i=0; i<6; i++ ) { + uint8_t line; + if (i == 5) + line = 0x0; + else + line = pgm_read_byte(font+(c*5)+i); + for (int8_t j = 0; j<8; j++) { + if (line & 0x1) { + if (size == 1) // default size + drawPixel(x+i, y+j, color); + else { // big size + fillRect(x+(i*size), y+(j*size), size, size, color); + } + } else if (bg != color) { + if (size == 1) // default size + drawPixel(x+i, y+j, bg); + else { // big size + fillRect(x+i*size, y+j*size, size, size, bg); + } + } + line >>= 1; + } + } +} + +void Adafruit_GFX::setCursor(int16_t x, int16_t y) { + cursor_x = x; + cursor_y = y; +} + + +void Adafruit_GFX::setTextSize(uint8_t s) { + textsize = (s > 0) ? s : 1; +} + + +void Adafruit_GFX::setTextColor(uint16_t c) { + textcolor = c; + textbgcolor = c; + // for 'transparent' background, we'll set the bg + // to the same as fg instead of using a flag +} + + void Adafruit_GFX::setTextColor(uint16_t c, uint16_t b) { + textcolor = c; + textbgcolor = b; + } + +void Adafruit_GFX::setTextWrap(boolean w) { + wrap = w; +} + +uint8_t Adafruit_GFX::getRotation(void) { + rotation %= 4; + return rotation; +} + +void Adafruit_GFX::setRotation(uint8_t x) { + x %= 4; // cant be higher than 3 + rotation = x; + switch (x) { + case 0: + case 2: + _width = WIDTH; + _height = HEIGHT; + break; + case 1: + case 3: + _width = HEIGHT; + _height = WIDTH; + break; + } +} + +void Adafruit_GFX::invertDisplay(boolean i) { + // do nothing, can be subclassed +} + + +// return the size of the display which depends on the rotation! +int16_t Adafruit_GFX::width(void) { + return _width; +} + +int16_t Adafruit_GFX::height(void) { + return _height; +} + + + +uint16_t Adafruit_GFX::newColor(uint8_t r, uint8_t g, uint8_t b) { + return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3); +} + + +void Adafruit_GFX::background(uint8_t red, uint8_t green, uint8_t blue) { + background(newColor(red, green, blue)); +} + +void Adafruit_GFX::background(color c) { + fillScreen(c); +} + +void Adafruit_GFX::stroke(uint8_t red, uint8_t green, uint8_t blue) { + stroke(newColor(red, green, blue)); +} + +void Adafruit_GFX::stroke(color c) { + useStroke = true; + strokeColor = c; + setTextColor(c); +} + +void Adafruit_GFX::noStroke() { + useStroke = false; +} + +void Adafruit_GFX::noFill() { + useFill = false; +} + +void Adafruit_GFX::fill(uint8_t red, uint8_t green, uint8_t blue) { + fill(newColor(red, green, blue)); +} + +void Adafruit_GFX::fill(color c) { + useFill = true; + fillColor = c; +} + + +void Adafruit_GFX::text(const char * text, int16_t x, int16_t y) { + if (!useStroke) + return; + + setTextWrap(false); + setTextColor(strokeColor); + setCursor(x, y); + print(text); +} + +void Adafruit_GFX::textWrap(const char * text, int16_t x, int16_t y) { + if (!useStroke) + return; + + setTextWrap(true); + setTextColor(strokeColor); + setCursor(x, y); + print(text); +} + + +void Adafruit_GFX::textSize(uint8_t size) { + setTextSize(size); +} + +void Adafruit_GFX::point(int16_t x, int16_t y) { + if (!useStroke) + return; + + drawPixel(x, y, strokeColor); +} + +void Adafruit_GFX::line(int16_t x1, int16_t y1, int16_t x2, int16_t y2) { + if (!useStroke) + return; + + if (x1 == x2) { + if (y1 < y2) + drawFastVLine(x1, y1, y2 - y1, strokeColor); + else + drawFastVLine(x1, y2, y1 - y2, strokeColor); + } + else if (y1 == y2) { + if (x1 < x2) + drawFastHLine(x1, y1, x2 - x1, strokeColor); + else + drawFastHLine(x2, y1, x1 - x2, strokeColor); + } + else { + drawLine(x1, y1, x2, y2, strokeColor); + } +} + +void Adafruit_GFX::rect(int16_t x, int16_t y, int16_t width, int16_t height) { + if (useFill) { + fillRect(x, y, width, height, fillColor); + } + if (useStroke) { + drawRect(x, y, width, height, strokeColor); + } +} + +void Adafruit_GFX::rect(int16_t x, int16_t y, int16_t width, int16_t height, int16_t radius) { + if (radius == 0) { + rect(x, y, width, height); + } + if (useFill) { + fillRoundRect(x, y, width, height, radius, fillColor); + } + if (useStroke) { + drawRoundRect(x, y, width, height, radius, strokeColor); + } +} + +void Adafruit_GFX::circle(int16_t x, int16_t y, int16_t r) { + if (r == 0) + return; + + if (useFill) { + fillCircle(x, y, r, fillColor); + } + if (useStroke) { + drawCircle(x, y, r, strokeColor); + } +} + +void Adafruit_GFX::triangle(int16_t x1, int16_t y1, int16_t x2, int16_t y2, int16_t x3, int16_t y3) { + if (useFill) { + fillTriangle(x1, y1, x2, y2, x3, y3, fillColor); + } + if (useStroke) { + drawTriangle(x1, y1, x2, y2, x3, y3, strokeColor); + } +} + +#if defined(__SD_H__) // Arduino SD library + +#define BUFFPIXEL 20 + +void Adafruit_GFX::image(PImage & img, uint16_t x, uint16_t y) { + int w, h, row, col; + uint8_t r, g, b; + uint32_t pos = 0; + uint8_t sdbuffer[3*BUFFPIXEL]; // pixel buffer (R+G+B per pixel) + uint8_t buffidx = sizeof(sdbuffer); // Current position in sdbuffer + + // Crop area to be loaded + w = img._bmpWidth; + h = img._bmpHeight; + if((x+w-1) >= width()) w = width() - x; + if((y+h-1) >= height()) h = height() - y; + + /* + // Set TFT address window to clipped image bounds + setAddrWindow(x, y, x+w-1, y+h-1); + */ + + for (row=0; row= sizeof(sdbuffer)) { // Indeed + img._bmpFile.read(sdbuffer, sizeof(sdbuffer)); + buffidx = 0; // Set index to beginning + } + + // Convert pixel from BMP to TFT format, push to display + b = sdbuffer[buffidx++]; + g = sdbuffer[buffidx++]; + r = sdbuffer[buffidx++]; + //pushColor(tft.Color565(r,g,b)); + drawPixel(x + col, y + row, newColor(r, g, b)); + + } // end pixel + } // end scanline + +} + +#endif \ No newline at end of file diff --git a/libraries/TFT/utility/Adafruit_GFX.h b/libraries/TFT/utility/Adafruit_GFX.h new file mode 100644 index 00000000000..b49aa0f33fe --- /dev/null +++ b/libraries/TFT/utility/Adafruit_GFX.h @@ -0,0 +1,367 @@ +/****************************************************************** + This is the core graphics library for all our displays, providing + basic graphics primitives (points, lines, circles, etc.). It needs + to be paired with a hardware-specific library for each display + device we carry (handling the lower-level functions). + + Adafruit invests time and resources providing this open + source code, please support Adafruit and open-source hardware + by purchasing products from Adafruit! + + Written by Limor Fried/Ladyada for Adafruit Industries. + Processing-like API written by Enrico Gueli for Officine Arduino. + BSD license, check license.txt for more information. + All text above must be included in any redistribution. + ******************************************************************/ + +#ifndef _ADAFRUIT_GFX_H +#define _ADAFRUIT_GFX_H + +#if ARDUINO >= 100 + #include "Arduino.h" + #include "Print.h" +#else + #include "WProgram.h" +#endif + +/* + * This library can work with or without the presence of an SD + * reading library (to load images). At the moment, only the + * Arduino SD library is supported; it is included in + * standard Arduino libraries. + * + * The presence of the SD library is detected by looking at the + * __SD_H__ preprocessor variable, defined into + * Arduino SD library to avoid double inclusion. This means + * that in order to use the image-related API of Adafruit_GFX, + * SD.h *must* be included before Adafruit_GFX. + * + * The bottom part of this include file contains the actual image + * loading code; if it was in a separate .cpp file, there were no + * way to check if the SD library was present or not. + * + * A partial solution was to include SD.h anyway, see if that works + * (i.e. it is found in the include search path) and act accordingly. + * But this solution relied on the preprocessor to issue only a + * warning when an include file is not found. Avr-gcc, used for + * Arduino 8-bit MCUs, does that, but the standard gcc-4.4, used for + * Arduino Due, issues a fatal error and stops compilation. + * + * The best solution so far is to put the code here. It works if this + * include is used only in one .cpp file in the build (this is the + * case of most Arduino sketches); if used in multiple .cpp files, + * the linker may complain about duplicate definitions. + * + */ + +#if defined(__SD_H__) // Arduino SD library +# include "PImage.h" +#else +# warning "The SD library was not found. loadImage() and image() won't be supported." +#endif + +#define swap(a, b) { int16_t t = a; a = b; b = t; } + +/* TODO +enum RectMode { + CORNER, + CORNERS, + RADIUS, + CENTER +}; +*/ + +typedef uint16_t color; + +class Adafruit_GFX : public Print { + public: + + //Adafruit_GFX(); + // i have no idea why we have to formally call the constructor. kinda sux + void constructor(int16_t w, int16_t h); + + // this must be defined by the subclass + virtual void drawPixel(int16_t x, int16_t y, uint16_t color); + virtual void invertDisplay(boolean i); + + // these are 'generic' drawing functions, so we can share them! + virtual void drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, + uint16_t color); + virtual void drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color); + virtual void drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color); + virtual void drawRect(int16_t x, int16_t y, int16_t w, int16_t h, + uint16_t color); + virtual void fillRect(int16_t x, int16_t y, int16_t w, int16_t h, + uint16_t color); + virtual void fillScreen(uint16_t color); + + void drawCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color); + void drawCircleHelper(int16_t x0, int16_t y0, + int16_t r, uint8_t cornername, uint16_t color); + void fillCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color); + void fillCircleHelper(int16_t x0, int16_t y0, int16_t r, + uint8_t cornername, int16_t delta, uint16_t color); + + void drawTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1, + int16_t x2, int16_t y2, uint16_t color); + void fillTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1, + int16_t x2, int16_t y2, uint16_t color); + void drawRoundRect(int16_t x0, int16_t y0, int16_t w, int16_t h, + int16_t radius, uint16_t color); + void fillRoundRect(int16_t x0, int16_t y0, int16_t w, int16_t h, + int16_t radius, uint16_t color); + + void drawBitmap(int16_t x, int16_t y, + const uint8_t *bitmap, int16_t w, int16_t h, + uint16_t color); + void drawChar(int16_t x, int16_t y, unsigned char c, + uint16_t color, uint16_t bg, uint8_t size); +#if ARDUINO >= 100 + virtual size_t write(uint8_t); +#else + virtual void write(uint8_t); +#endif + void setCursor(int16_t x, int16_t y); + void setTextColor(uint16_t c); + void setTextColor(uint16_t c, uint16_t bg); + void setTextSize(uint8_t s); + void setTextWrap(boolean w); + + int16_t height(void); + int16_t width(void); + + void setRotation(uint8_t r); + uint8_t getRotation(void); + + + /* + * Processing-like graphics primitives + */ + + /// transforms a color in 16-bit form given the RGB components. + /// The default implementation makes a 5-bit red, a 6-bit + /// green and a 5-bit blue (MSB to LSB). Devices that use + /// different scheme should override this. + virtual uint16_t newColor(uint8_t red, uint8_t green, uint8_t blue); + + + // http://processing.org/reference/background_.html + void background(uint8_t red, uint8_t green, uint8_t blue); + void background(color c); + + // http://processing.org/reference/fill_.html + void fill(uint8_t red, uint8_t green, uint8_t blue); + void fill(color c); + + // http://processing.org/reference/noFill_.html + void noFill(); + + // http://processing.org/reference/stroke_.html + void stroke(uint8_t red, uint8_t green, uint8_t blue); + void stroke(color c); + + // http://processing.org/reference/noStroke_.html + void noStroke(); + + void text (const char * text, int16_t x, int16_t y); + void textWrap(const char * text, int16_t x, int16_t y); + + void textSize(uint8_t size); + + // similar to ellipse() in Processing, but with + // a single radius. + // http://processing.org/reference/ellipse_.html + void circle(int16_t x, int16_t y, int16_t r); + + void point(int16_t x, int16_t y); + + void line(int16_t x1, int16_t y1, int16_t x2, int16_t y2); + + void quad(int16_t x1, int16_t y1, int16_t x2, int16_t y2, int16_t x3, int16_t y3, int16_t x4, int16_t y4); + + void rect(int16_t x, int16_t y, int16_t width, int16_t height); + + void rect(int16_t x, int16_t y, int16_t width, int16_t height, int16_t radius); + + void triangle(int16_t x1, int16_t y1, int16_t x2, int16_t y2, int16_t x3, int16_t y3); + + /* TODO + void rectMode(RectMode mode); + + void pushStyle(); + void popStyle(); + */ + +#if defined(__SD_H__) // Arduino SD library + PImage loadImage(const char * fileName) { return PImage::loadImage(fileName); } + + void image(PImage & img, uint16_t x, uint16_t y); +#endif + + protected: + int16_t WIDTH, HEIGHT; // this is the 'raw' display w/h - never changes + int16_t _width, _height; // dependent on rotation + int16_t cursor_x, cursor_y; + uint16_t textcolor, textbgcolor; + uint8_t textsize; + uint8_t rotation; + boolean wrap; // If set, 'wrap' text at right edge of display + + /* + * Processing-style graphics state + */ + + color strokeColor; + bool useStroke; + color fillColor; + bool useFill; +}; + +#if defined(__SD_H__) // Arduino SD library + +#define BUFFPIXEL 20 + +void Adafruit_GFX::image(PImage & img, uint16_t x, uint16_t y) { + int w, h, row, col; + uint8_t r, g, b; + uint32_t pos = 0; + uint8_t sdbuffer[3*BUFFPIXEL]; // pixel buffer (R+G+B per pixel) + uint8_t buffidx = sizeof(sdbuffer); // Current position in sdbuffer + + // Crop area to be loaded + w = img._bmpWidth; + h = img._bmpHeight; + if((x+w-1) >= width()) w = width() - x; + if((y+h-1) >= height()) h = height() - y; + + /* + // Set TFT address window to clipped image bounds + setAddrWindow(x, y, x+w-1, y+h-1); + */ + + for (row=0; row= sizeof(sdbuffer)) { // Indeed + img._bmpFile.read(sdbuffer, sizeof(sdbuffer)); + buffidx = 0; // Set index to beginning + } + + // Convert pixel from BMP to TFT format, push to display + b = sdbuffer[buffidx++]; + g = sdbuffer[buffidx++]; + r = sdbuffer[buffidx++]; + //pushColor(tft.Color565(r,g,b)); + drawPixel(x + col, y + row, newColor(r, g, b)); + + } // end pixel + } // end scanline + +} + + + + +// These read 16- and 32-bit types from the SD card file. +// BMP data is stored little-endian, Arduino is little-endian too. +// May need to reverse subscript order if porting elsewhere. + +uint16_t PImage::read16(File f) { + uint16_t result; + ((uint8_t *)&result)[0] = f.read(); // LSB + ((uint8_t *)&result)[1] = f.read(); // MSB + return result; +} + +uint32_t PImage::read32(File f) { + uint32_t result; + ((uint8_t *)&result)[0] = f.read(); // LSB + ((uint8_t *)&result)[1] = f.read(); + ((uint8_t *)&result)[2] = f.read(); + ((uint8_t *)&result)[3] = f.read(); // MSB + return result; +} + + +PImage PImage::loadImage(const char * fileName) { + File bmpFile; + int bmpWidth, bmpHeight; // W+H in pixels + uint8_t bmpDepth; // Bit depth (currently must be 24) + uint32_t bmpImageoffset; // Start of image data in file + uint32_t rowSize; // Not always = bmpWidth; may have padding + bool flip = true; // BMP is stored bottom-to-top + + + // Open requested file on SD card + if ((bmpFile = SD.open(fileName)) == NULL) { + Serial.print("loadImage: file not found: "); + Serial.println(fileName); + return PImage(); // load error + } + + + + // Parse BMP header + if(read16(bmpFile) != 0x4D42) { // BMP signature + Serial.println("loadImage: file doesn't look like a BMP"); + return PImage(); + } + + Serial.print("File size: "); Serial.println(read32(bmpFile)); + (void)read32(bmpFile); // Read & ignore creator bytes + bmpImageoffset = read32(bmpFile); // Start of image data + Serial.print("Image Offset: "); Serial.println(bmpImageoffset, DEC); + // Read DIB header + Serial.print("Header size: "); Serial.println(read32(bmpFile)); + bmpWidth = read32(bmpFile); + bmpHeight = read32(bmpFile); + if(read16(bmpFile) != 1) { // # planes -- must be '1' + Serial.println("loadImage: invalid n. of planes"); + return PImage(); + } + + bmpDepth = read16(bmpFile); // bits per pixel + Serial.print("Bit Depth: "); Serial.println(bmpDepth); + if((bmpDepth != 24) || (read32(bmpFile) != 0)) { // 0 = uncompressed { + Serial.println("loadImage: invalid pixel format"); + return PImage(); + } + + Serial.print("Image size: "); + Serial.print(bmpWidth); + Serial.print('x'); + Serial.println(bmpHeight); + + // BMP rows are padded (if needed) to 4-byte boundary + rowSize = (bmpWidth * 3 + 3) & ~3; + + // If bmpHeight is negative, image is in top-down order. + // This is not canon but has been observed in the wild. + if(bmpHeight < 0) { + bmpHeight = -bmpHeight; + flip = false; + } + + return PImage(bmpFile, bmpWidth, bmpHeight, bmpDepth, bmpImageoffset, rowSize, flip); +} + +#endif + + + +#endif diff --git a/libraries/TFT/utility/Adafruit_ST7735.cpp b/libraries/TFT/utility/Adafruit_ST7735.cpp new file mode 100755 index 00000000000..ed57bf72bdd --- /dev/null +++ b/libraries/TFT/utility/Adafruit_ST7735.cpp @@ -0,0 +1,603 @@ +/*************************************************** + This is a library for the Adafruit 1.8" SPI display. + This library works with the Adafruit 1.8" TFT Breakout w/SD card + ----> http://www.adafruit.com/products/358 + as well as Adafruit raw 1.8" TFT display + ----> http://www.adafruit.com/products/618 + + Check out the links above for our tutorials and wiring diagrams + These displays use SPI to communicate, 4 or 5 pins are required to + interface (RST is optional) + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing + products from Adafruit! + + Written by Limor Fried/Ladyada for Adafruit Industries. + MIT license, all text above must be included in any redistribution + ****************************************************/ + +#include "Adafruit_ST7735.h" +#include +#include +#include "pins_arduino.h" +#include "wiring_private.h" +#include + +inline uint16_t swapcolor(uint16_t x) { + return (x << 11) | (x & 0x07E0) | (x >> 11); +} + + +// Constructor when using software SPI. All output pins are configurable. +Adafruit_ST7735::Adafruit_ST7735(uint8_t cs, uint8_t rs, uint8_t sid, + uint8_t sclk, uint8_t rst) { + _cs = cs; + _rs = rs; + _sid = sid; + _sclk = sclk; + _rst = rst; + hwSPI = false; +} + + +// Constructor when using hardware SPI. Faster, but must use SPI pins +// specific to each board type (e.g. 11,13 for Uno, 51,52 for Mega, etc.) +Adafruit_ST7735::Adafruit_ST7735(uint8_t cs, uint8_t rs, uint8_t rst) { + _cs = cs; + _rs = rs; + _rst = rst; + hwSPI = true; + _sid = _sclk = 0; +} + + +inline void Adafruit_ST7735::spiwrite(uint8_t c) { + + //Serial.println(c, HEX); + + if (hwSPI) { + SPI.transfer(c); + } else { + // Fast SPI bitbang swiped from LPD8806 library + for(uint8_t bit = 0x80; bit; bit >>= 1) { + if(c & bit) *dataport |= datapinmask; + else *dataport &= ~datapinmask; + *clkport |= clkpinmask; + *clkport &= ~clkpinmask; + } + } +} + + +void Adafruit_ST7735::writecommand(uint8_t c) { + *rsport &= ~rspinmask; + *csport &= ~cspinmask; + + //Serial.print("C "); + spiwrite(c); + + *csport |= cspinmask; +} + + +void Adafruit_ST7735::writedata(uint8_t c) { + *rsport |= rspinmask; + *csport &= ~cspinmask; + + //Serial.print("D "); + spiwrite(c); + + *csport |= cspinmask; +} + + +// Rather than a bazillion writecommand() and writedata() calls, screen +// initialization commands and arguments are organized in these tables +// stored in PROGMEM. The table may look bulky, but that's mostly the +// formatting -- storage-wise this is hundreds of bytes more compact +// than the equivalent code. Companion function follows. +#define DELAY 0x80 +PROGMEM static prog_uchar + Bcmd[] = { // Initialization commands for 7735B screens + 18, // 18 commands in list: + ST7735_SWRESET, DELAY, // 1: Software reset, no args, w/delay + 50, // 50 ms delay + ST7735_SLPOUT , DELAY, // 2: Out of sleep mode, no args, w/delay + 255, // 255 = 500 ms delay + ST7735_COLMOD , 1+DELAY, // 3: Set color mode, 1 arg + delay: + 0x05, // 16-bit color + 10, // 10 ms delay + ST7735_FRMCTR1, 3+DELAY, // 4: Frame rate control, 3 args + delay: + 0x00, // fastest refresh + 0x06, // 6 lines front porch + 0x03, // 3 lines back porch + 10, // 10 ms delay + ST7735_MADCTL , 1 , // 5: Memory access ctrl (directions), 1 arg: + 0x08, // Row addr/col addr, bottom to top refresh + ST7735_DISSET5, 2 , // 6: Display settings #5, 2 args, no delay: + 0x15, // 1 clk cycle nonoverlap, 2 cycle gate + // rise, 3 cycle osc equalize + 0x02, // Fix on VTL + ST7735_INVCTR , 1 , // 7: Display inversion control, 1 arg: + 0x0, // Line inversion + ST7735_PWCTR1 , 2+DELAY, // 8: Power control, 2 args + delay: + 0x02, // GVDD = 4.7V + 0x70, // 1.0uA + 10, // 10 ms delay + ST7735_PWCTR2 , 1 , // 9: Power control, 1 arg, no delay: + 0x05, // VGH = 14.7V, VGL = -7.35V + ST7735_PWCTR3 , 2 , // 10: Power control, 2 args, no delay: + 0x01, // Opamp current small + 0x02, // Boost frequency + ST7735_VMCTR1 , 2+DELAY, // 11: Power control, 2 args + delay: + 0x3C, // VCOMH = 4V + 0x38, // VCOML = -1.1V + 10, // 10 ms delay + ST7735_PWCTR6 , 2 , // 12: Power control, 2 args, no delay: + 0x11, 0x15, + ST7735_GMCTRP1,16 , // 13: Magical unicorn dust, 16 args, no delay: + 0x09, 0x16, 0x09, 0x20, // (seriously though, not sure what + 0x21, 0x1B, 0x13, 0x19, // these config values represent) + 0x17, 0x15, 0x1E, 0x2B, + 0x04, 0x05, 0x02, 0x0E, + ST7735_GMCTRN1,16+DELAY, // 14: Sparkles and rainbows, 16 args + delay: + 0x0B, 0x14, 0x08, 0x1E, // (ditto) + 0x22, 0x1D, 0x18, 0x1E, + 0x1B, 0x1A, 0x24, 0x2B, + 0x06, 0x06, 0x02, 0x0F, + 10, // 10 ms delay + ST7735_CASET , 4 , // 15: Column addr set, 4 args, no delay: + 0x00, 0x02, // XSTART = 2 + 0x00, 0x81, // XEND = 129 + ST7735_RASET , 4 , // 16: Row addr set, 4 args, no delay: + 0x00, 0x02, // XSTART = 1 + 0x00, 0x81, // XEND = 160 + ST7735_NORON , DELAY, // 17: Normal display on, no args, w/delay + 10, // 10 ms delay + ST7735_DISPON , DELAY, // 18: Main screen turn on, no args, w/delay + 255 }, // 255 = 500 ms delay + + Rcmd1[] = { // Init for 7735R, part 1 (red or green tab) + 15, // 15 commands in list: + ST7735_SWRESET, DELAY, // 1: Software reset, 0 args, w/delay + 150, // 150 ms delay + ST7735_SLPOUT , DELAY, // 2: Out of sleep mode, 0 args, w/delay + 255, // 500 ms delay + ST7735_FRMCTR1, 3 , // 3: Frame rate ctrl - normal mode, 3 args: + 0x01, 0x2C, 0x2D, // Rate = fosc/(1x2+40) * (LINE+2C+2D) + ST7735_FRMCTR2, 3 , // 4: Frame rate control - idle mode, 3 args: + 0x01, 0x2C, 0x2D, // Rate = fosc/(1x2+40) * (LINE+2C+2D) + ST7735_FRMCTR3, 6 , // 5: Frame rate ctrl - partial mode, 6 args: + 0x01, 0x2C, 0x2D, // Dot inversion mode + 0x01, 0x2C, 0x2D, // Line inversion mode + ST7735_INVCTR , 1 , // 6: Display inversion ctrl, 1 arg, no delay: + 0x07, // No inversion + ST7735_PWCTR1 , 3 , // 7: Power control, 3 args, no delay: + 0xA2, + 0x02, // -4.6V + 0x84, // AUTO mode + ST7735_PWCTR2 , 1 , // 8: Power control, 1 arg, no delay: + 0xC5, // VGH25 = 2.4C VGSEL = -10 VGH = 3 * AVDD + ST7735_PWCTR3 , 2 , // 9: Power control, 2 args, no delay: + 0x0A, // Opamp current small + 0x00, // Boost frequency + ST7735_PWCTR4 , 2 , // 10: Power control, 2 args, no delay: + 0x8A, // BCLK/2, Opamp current small & Medium low + 0x2A, + ST7735_PWCTR5 , 2 , // 11: Power control, 2 args, no delay: + 0x8A, 0xEE, + ST7735_VMCTR1 , 1 , // 12: Power control, 1 arg, no delay: + 0x0E, + ST7735_INVOFF , 0 , // 13: Don't invert display, no args, no delay + ST7735_MADCTL , 1 , // 14: Memory access control (directions), 1 arg: + 0xC8, // row addr/col addr, bottom to top refresh + ST7735_COLMOD , 1 , // 15: set color mode, 1 arg, no delay: + 0x05 }, // 16-bit color + + Rcmd2green[] = { // Init for 7735R, part 2 (green tab only) + 2, // 2 commands in list: + ST7735_CASET , 4 , // 1: Column addr set, 4 args, no delay: + 0x00, 0x02, // XSTART = 0 + 0x00, 0x7F+0x02, // XEND = 127 + ST7735_RASET , 4 , // 2: Row addr set, 4 args, no delay: + 0x00, 0x01, // XSTART = 0 + 0x00, 0x9F+0x01 }, // XEND = 159 + Rcmd2red[] = { // Init for 7735R, part 2 (red tab only) + 2, // 2 commands in list: + ST7735_CASET , 4 , // 1: Column addr set, 4 args, no delay: + 0x00, 0x00, // XSTART = 0 + 0x00, 0x7F, // XEND = 127 + ST7735_RASET , 4 , // 2: Row addr set, 4 args, no delay: + 0x00, 0x00, // XSTART = 0 + 0x00, 0x9F }, // XEND = 159 + + Rcmd3[] = { // Init for 7735R, part 3 (red or green tab) + 4, // 4 commands in list: + ST7735_GMCTRP1, 16 , // 1: Magical unicorn dust, 16 args, no delay: + 0x02, 0x1c, 0x07, 0x12, + 0x37, 0x32, 0x29, 0x2d, + 0x29, 0x25, 0x2B, 0x39, + 0x00, 0x01, 0x03, 0x10, + ST7735_GMCTRN1, 16 , // 2: Sparkles and rainbows, 16 args, no delay: + 0x03, 0x1d, 0x07, 0x06, + 0x2E, 0x2C, 0x29, 0x2D, + 0x2E, 0x2E, 0x37, 0x3F, + 0x00, 0x00, 0x02, 0x10, + ST7735_NORON , DELAY, // 3: Normal display on, no args, w/delay + 10, // 10 ms delay + ST7735_DISPON , DELAY, // 4: Main screen turn on, no args w/delay + 100 }; // 100 ms delay + + +// Companion code to the above tables. Reads and issues +// a series of LCD commands stored in PROGMEM byte array. +void Adafruit_ST7735::commandList(uint8_t *addr) { + + uint8_t numCommands, numArgs; + uint16_t ms; + + numCommands = pgm_read_byte(addr++); // Number of commands to follow + while(numCommands--) { // For each command... + writecommand(pgm_read_byte(addr++)); // Read, issue command + numArgs = pgm_read_byte(addr++); // Number of args to follow + ms = numArgs & DELAY; // If hibit set, delay follows args + numArgs &= ~DELAY; // Mask out delay bit + while(numArgs--) { // For each argument... + writedata(pgm_read_byte(addr++)); // Read, issue argument + } + + if(ms) { + ms = pgm_read_byte(addr++); // Read post-command delay time (ms) + if(ms == 255) ms = 500; // If 255, delay for 500 ms + delay(ms); + } + } +} + + +// Initialization code common to both 'B' and 'R' type displays +void Adafruit_ST7735::commonInit(uint8_t *cmdList) { + + constructor(ST7735_TFTWIDTH, ST7735_TFTHEIGHT); + colstart = rowstart = 0; // May be overridden in init func + + pinMode(_rs, OUTPUT); + pinMode(_cs, OUTPUT); + csport = portOutputRegister(digitalPinToPort(_cs)); + cspinmask = digitalPinToBitMask(_cs); + rsport = portOutputRegister(digitalPinToPort(_rs)); + rspinmask = digitalPinToBitMask(_rs); + + if(hwSPI) { // Using hardware SPI + SPI.begin(); +#if defined(ARDUINO_ARCH_SAM) + SPI.setClockDivider(24); // 4 MHz (half speed) +#else + SPI.setClockDivider(SPI_CLOCK_DIV4); // 4 MHz (half speed) +#endif + SPI.setBitOrder(MSBFIRST); + SPI.setDataMode(SPI_MODE0); + } else { + pinMode(_sclk, OUTPUT); + pinMode(_sid , OUTPUT); + clkport = portOutputRegister(digitalPinToPort(_sclk)); + clkpinmask = digitalPinToBitMask(_sclk); + dataport = portOutputRegister(digitalPinToPort(_sid)); + datapinmask = digitalPinToBitMask(_sid); + *clkport &= ~clkpinmask; + *dataport &= ~datapinmask; + } + + // toggle RST low to reset; CS low so it'll listen to us + *csport &= ~cspinmask; + if (_rst) { + pinMode(_rst, OUTPUT); + digitalWrite(_rst, HIGH); + delay(500); + digitalWrite(_rst, LOW); + delay(500); + digitalWrite(_rst, HIGH); + delay(500); + } + + if(cmdList) commandList(cmdList); +} + + +// Initialization for ST7735B screens +void Adafruit_ST7735::initB(void) { + commonInit(Bcmd); +} + + +// Initialization for ST7735R screens (green or red tabs) +void Adafruit_ST7735::initR(uint8_t options) { + commonInit(Rcmd1); + if(options == INITR_GREENTAB) { + commandList(Rcmd2green); + colstart = 2; + rowstart = 1; + } else { + // colstart, rowstart left at default '0' values + commandList(Rcmd2red); + } + commandList(Rcmd3); + tabcolor = options; +} + + +void Adafruit_ST7735::setAddrWindow(uint8_t x0, uint8_t y0, uint8_t x1, + uint8_t y1) { + + writecommand(ST7735_CASET); // Column addr set + writedata(0x00); + writedata(x0+colstart); // XSTART + writedata(0x00); + writedata(x1+colstart); // XEND + + writecommand(ST7735_RASET); // Row addr set + writedata(0x00); + writedata(y0+rowstart); // YSTART + writedata(0x00); + writedata(y1+rowstart); // YEND + + writecommand(ST7735_RAMWR); // write to RAM +} + + +void Adafruit_ST7735::pushColor(uint16_t color) { + *rsport |= rspinmask; + *csport &= ~cspinmask; + + if (tabcolor == INITR_BLACKTAB) color = swapcolor(color); + spiwrite(color >> 8); + spiwrite(color); + + *csport |= cspinmask; +} + +void Adafruit_ST7735::drawPixel(int16_t x, int16_t y, uint16_t color) { + + if((x < 0) ||(x >= _width) || (y < 0) || (y >= _height)) return; + + setAddrWindow(x,y,x+1,y+1); + + *rsport |= rspinmask; + *csport &= ~cspinmask; + + if (tabcolor == INITR_BLACKTAB) color = swapcolor(color); + + spiwrite(color >> 8); + spiwrite(color); + + *csport |= cspinmask; +} + + +void Adafruit_ST7735::drawFastVLine(int16_t x, int16_t y, int16_t h, + uint16_t color) { + + // Rudimentary clipping + if((x >= _width) || (y >= _height)) return; + if((y+h-1) >= _height) h = _height-y; + setAddrWindow(x, y, x, y+h-1); + + if (tabcolor == INITR_BLACKTAB) color = swapcolor(color); + + uint8_t hi = color >> 8, lo = color; + *rsport |= rspinmask; + *csport &= ~cspinmask; + while (h--) { + spiwrite(hi); + spiwrite(lo); + } + *csport |= cspinmask; +} + + +void Adafruit_ST7735::drawFastHLine(int16_t x, int16_t y, int16_t w, + uint16_t color) { + + // Rudimentary clipping + if((x >= _width) || (y >= _height)) return; + if((x+w-1) >= _width) w = _width-x; + setAddrWindow(x, y, x+w-1, y); + + if (tabcolor == INITR_BLACKTAB) color = swapcolor(color); + + uint8_t hi = color >> 8, lo = color; + *rsport |= rspinmask; + *csport &= ~cspinmask; + while (w--) { + spiwrite(hi); + spiwrite(lo); + } + *csport |= cspinmask; +} + + + +void Adafruit_ST7735::fillScreen(uint16_t color) { + fillRect(0, 0, _width, _height, color); +} + + + +// fill a rectangle +void Adafruit_ST7735::fillRect(int16_t x, int16_t y, int16_t w, int16_t h, + uint16_t color) { + + // rudimentary clipping (drawChar w/big text requires this) + if((x >= _width) || (y >= _height)) return; + if((x + w - 1) >= _width) w = _width - x; + if((y + h - 1) >= _height) h = _height - y; + + if (tabcolor == INITR_BLACKTAB) color = swapcolor(color); + + setAddrWindow(x, y, x+w-1, y+h-1); + + uint8_t hi = color >> 8, lo = color; + *rsport |= rspinmask; + *csport &= ~cspinmask; + for(y=h; y>0; y--) { + for(x=w; x>0; x--) { + spiwrite(hi); + spiwrite(lo); + } + } + + *csport |= cspinmask; +} + + +#define MADCTL_MY 0x80 +#define MADCTL_MX 0x40 +#define MADCTL_MV 0x20 +#define MADCTL_ML 0x10 +#define MADCTL_RGB 0x08 +#define MADCTL_MH 0x04 + +void Adafruit_ST7735::setRotation(uint8_t m) { + + writecommand(ST7735_MADCTL); + rotation = m % 4; // can't be higher than 3 + switch (rotation) { + case 0: + writedata(MADCTL_MX | MADCTL_MY | MADCTL_RGB); + _width = ST7735_TFTWIDTH; + _height = ST7735_TFTHEIGHT; + break; + case 1: + writedata(MADCTL_MY | MADCTL_MV | MADCTL_RGB); + _width = ST7735_TFTHEIGHT; + _height = ST7735_TFTWIDTH; + break; + case 2: + writedata(MADCTL_RGB); + _width = ST7735_TFTWIDTH; + _height = ST7735_TFTHEIGHT; + break; + case 3: + writedata(MADCTL_MX | MADCTL_MV | MADCTL_RGB); + _width = ST7735_TFTHEIGHT; + _height = ST7735_TFTWIDTH; + break; + } +} + + +void Adafruit_ST7735::invertDisplay(boolean i) { + writecommand(i ? ST7735_INVON : ST7735_INVOFF); +} + + +////////// stuff not actively being used, but kept for posterity +/* + + uint8_t Adafruit_ST7735::spiread(void) { + uint8_t r = 0; + if (_sid > 0) { + r = shiftIn(_sid, _sclk, MSBFIRST); + } else { + //SID_DDR &= ~_BV(SID); + //int8_t i; + //for (i=7; i>=0; i--) { + // SCLK_PORT &= ~_BV(SCLK); + // r <<= 1; + // r |= (SID_PIN >> SID) & 0x1; + // SCLK_PORT |= _BV(SCLK); + //} + //SID_DDR |= _BV(SID); + + } + return r; + } + + + void Adafruit_ST7735::dummyclock(void) { + + if (_sid > 0) { + digitalWrite(_sclk, LOW); + digitalWrite(_sclk, HIGH); + } else { + // SCLK_PORT &= ~_BV(SCLK); + //SCLK_PORT |= _BV(SCLK); + } + } + uint8_t Adafruit_ST7735::readdata(void) { + *portOutputRegister(rsport) |= rspin; + + *portOutputRegister(csport) &= ~ cspin; + + uint8_t r = spiread(); + + *portOutputRegister(csport) |= cspin; + + return r; + + } + + uint8_t Adafruit_ST7735::readcommand8(uint8_t c) { + digitalWrite(_rs, LOW); + + *portOutputRegister(csport) &= ~ cspin; + + spiwrite(c); + + digitalWrite(_rs, HIGH); + pinMode(_sid, INPUT); // input! + digitalWrite(_sid, LOW); // low + spiread(); + uint8_t r = spiread(); + + + *portOutputRegister(csport) |= cspin; + + + pinMode(_sid, OUTPUT); // back to output + return r; + } + + + uint16_t Adafruit_ST7735::readcommand16(uint8_t c) { + digitalWrite(_rs, LOW); + if (_cs) + digitalWrite(_cs, LOW); + + spiwrite(c); + pinMode(_sid, INPUT); // input! + uint16_t r = spiread(); + r <<= 8; + r |= spiread(); + if (_cs) + digitalWrite(_cs, HIGH); + + pinMode(_sid, OUTPUT); // back to output + return r; + } + + uint32_t Adafruit_ST7735::readcommand32(uint8_t c) { + digitalWrite(_rs, LOW); + if (_cs) + digitalWrite(_cs, LOW); + spiwrite(c); + pinMode(_sid, INPUT); // input! + + dummyclock(); + dummyclock(); + + uint32_t r = spiread(); + r <<= 8; + r |= spiread(); + r <<= 8; + r |= spiread(); + r <<= 8; + r |= spiread(); + if (_cs) + digitalWrite(_cs, HIGH); + + pinMode(_sid, OUTPUT); // back to output + return r; + } + + */ diff --git a/libraries/TFT/utility/Adafruit_ST7735.h b/libraries/TFT/utility/Adafruit_ST7735.h new file mode 100755 index 00000000000..c0d5de08662 --- /dev/null +++ b/libraries/TFT/utility/Adafruit_ST7735.h @@ -0,0 +1,150 @@ +/*************************************************** + This is a library for the Adafruit 1.8" SPI display. + This library works with the Adafruit 1.8" TFT Breakout w/SD card + ----> http://www.adafruit.com/products/358 + as well as Adafruit raw 1.8" TFT display + ----> http://www.adafruit.com/products/618 + + Check out the links above for our tutorials and wiring diagrams + These displays use SPI to communicate, 4 or 5 pins are required to + interface (RST is optional) + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing + products from Adafruit! + + Written by Limor Fried/Ladyada for Adafruit Industries. + MIT license, all text above must be included in any redistribution + ****************************************************/ + +#ifndef _ADAFRUIT_ST7735H_ +#define _ADAFRUIT_ST7735H_ + +#if ARDUINO >= 100 + #include "Arduino.h" + #include "Print.h" +#else + #include "WProgram.h" +#endif +#include +#include + +// some flags for initR() :( +#define INITR_GREENTAB 0x0 +#define INITR_REDTAB 0x1 +#define INITR_BLACKTAB 0x2 + +#define ST7735_TFTWIDTH 128 +#define ST7735_TFTHEIGHT 160 + +#define ST7735_NOP 0x00 +#define ST7735_SWRESET 0x01 +#define ST7735_RDDID 0x04 +#define ST7735_RDDST 0x09 + +#define ST7735_SLPIN 0x10 +#define ST7735_SLPOUT 0x11 +#define ST7735_PTLON 0x12 +#define ST7735_NORON 0x13 + +#define ST7735_INVOFF 0x20 +#define ST7735_INVON 0x21 +#define ST7735_DISPOFF 0x28 +#define ST7735_DISPON 0x29 +#define ST7735_CASET 0x2A +#define ST7735_RASET 0x2B +#define ST7735_RAMWR 0x2C +#define ST7735_RAMRD 0x2E + +#define ST7735_PTLAR 0x30 +#define ST7735_COLMOD 0x3A +#define ST7735_MADCTL 0x36 + +#define ST7735_FRMCTR1 0xB1 +#define ST7735_FRMCTR2 0xB2 +#define ST7735_FRMCTR3 0xB3 +#define ST7735_INVCTR 0xB4 +#define ST7735_DISSET5 0xB6 + +#define ST7735_PWCTR1 0xC0 +#define ST7735_PWCTR2 0xC1 +#define ST7735_PWCTR3 0xC2 +#define ST7735_PWCTR4 0xC3 +#define ST7735_PWCTR5 0xC4 +#define ST7735_VMCTR1 0xC5 + +#define ST7735_RDID1 0xDA +#define ST7735_RDID2 0xDB +#define ST7735_RDID3 0xDC +#define ST7735_RDID4 0xDD + +#define ST7735_PWCTR6 0xFC + +#define ST7735_GMCTRP1 0xE0 +#define ST7735_GMCTRN1 0xE1 + +// Color definitions +#define ST7735_BLACK 0x0000 +#define ST7735_BLUE 0x001F +#define ST7735_RED 0xF800 +#define ST7735_GREEN 0x07E0 +#define ST7735_CYAN 0x07FF +#define ST7735_MAGENTA 0xF81F +#define ST7735_YELLOW 0xFFE0 +#define ST7735_WHITE 0xFFFF + + +class Adafruit_ST7735 : public Adafruit_GFX { + + public: + + Adafruit_ST7735(uint8_t CS, uint8_t RS, uint8_t SID, uint8_t SCLK, + uint8_t RST); + Adafruit_ST7735(uint8_t CS, uint8_t RS, uint8_t RST); + + void initB(void), // for ST7735B displays + initR(uint8_t options = INITR_GREENTAB), // for ST7735R + setAddrWindow(uint8_t x0, uint8_t y0, uint8_t x1, uint8_t y1), + pushColor(uint16_t color), + fillScreen(uint16_t color), + drawPixel(int16_t x, int16_t y, uint16_t color), + drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color), + drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color), + fillRect(int16_t x, int16_t y, int16_t w, int16_t h, + uint16_t color), + setRotation(uint8_t r), + invertDisplay(boolean i); + uint16_t Color565(uint8_t r, uint8_t g, uint8_t b) { return newColor(r, g, b);} + + /* These are not for current use, 8-bit protocol only! + uint8_t readdata(void), + readcommand8(uint8_t); + uint16_t readcommand16(uint8_t); + uint32_t readcommand32(uint8_t); + void dummyclock(void); + */ + + private: + uint8_t tabcolor; + + void spiwrite(uint8_t), + writecommand(uint8_t c), + writedata(uint8_t d), + commandList(uint8_t *addr), + commonInit(uint8_t *cmdList); +//uint8_t spiread(void); + + boolean hwSPI; + #if defined(ARDUINO_ARCH_SAM) + volatile uint32_t *dataport, *clkport, *csport, *rsport; + uint32_t _cs, _rs, _rst, _sid, _sclk, + datapinmask, clkpinmask, cspinmask, rspinmask, + colstart, rowstart; // some displays need this changed + #else + volatile uint8_t *dataport, *clkport, *csport, *rsport; + uint8_t _cs, _rs, _rst, _sid, _sclk, + datapinmask, clkpinmask, cspinmask, rspinmask, + colstart, rowstart; // some displays need this changed + #endif +}; + +#endif diff --git a/libraries/TFT/utility/PImage.h b/libraries/TFT/utility/PImage.h new file mode 100644 index 00000000000..d37bf71f3c9 --- /dev/null +++ b/libraries/TFT/utility/PImage.h @@ -0,0 +1,64 @@ + + +#ifndef _PIMAGE_H +#define _PIMAGE_H + +class Adafruit_GFX; + +#if defined(__SD_H__) // Arduino SD library + + +/// This class mimics Processing's PImage, but with fewer +/// capabilities. It allows an image stored in the SD card to be +/// drawn to the display. +/// @author Enrico Gueli +class PImage { +public: + PImage() : + _valid(false), + _bmpWidth(0), + _bmpHeight(0) { } + + void draw(Adafruit_GFX & glcd, int16_t x, int16_t y); + + static PImage loadImage(const char * fileName); + + + bool isValid() { return _valid; } + + int width() { return _bmpWidth; } + int height() { return _bmpHeight; } + +private: + friend class Adafruit_GFX; + + File _bmpFile; + int _bmpWidth, _bmpHeight; // W+H in pixels + uint8_t _bmpDepth; // Bit depth (currently must be 24) + uint32_t _bmpImageoffset; // Start of image data in file + uint32_t _rowSize; // Not always = bmpWidth; may have padding + bool _flip; + + bool _valid; + + PImage(File & bmpFile, int bmpWidth, int bmpHeight, uint8_t bmpDepth, uint32_t bmpImageoffset, uint32_t rowSize, bool flip) : + _bmpFile(bmpFile), + _bmpWidth(bmpWidth), + _bmpHeight(bmpHeight), + _bmpDepth(bmpDepth), + _bmpImageoffset(bmpImageoffset), + _rowSize(rowSize), + _flip(flip), + _valid(true) // since Adafruit_GFX is friend, we could just let it write the variables and save some CPU cycles + { } + + static uint16_t read16(File f); + static uint32_t read32(File f); + + // TODO close the file in ~PImage and PImage(const PImage&) + +}; + +#endif + +#endif // _PIMAGE_H diff --git a/libraries/TFT/utility/glcdfont.c b/libraries/TFT/utility/glcdfont.c new file mode 100644 index 00000000000..a325057214f --- /dev/null +++ b/libraries/TFT/utility/glcdfont.c @@ -0,0 +1,268 @@ +#ifndef ARDUINO_ARCH_SAM +#include +#endif +#include + +#ifndef FONT5X7_H +#define FONT5X7_H + +// standard ascii 5x7 font + +static unsigned char font[] PROGMEM = { + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x3E, 0x5B, 0x4F, 0x5B, 0x3E, + 0x3E, 0x6B, 0x4F, 0x6B, 0x3E, + 0x1C, 0x3E, 0x7C, 0x3E, 0x1C, + 0x18, 0x3C, 0x7E, 0x3C, 0x18, + 0x1C, 0x57, 0x7D, 0x57, 0x1C, + 0x1C, 0x5E, 0x7F, 0x5E, 0x1C, + 0x00, 0x18, 0x3C, 0x18, 0x00, + 0xFF, 0xE7, 0xC3, 0xE7, 0xFF, + 0x00, 0x18, 0x24, 0x18, 0x00, + 0xFF, 0xE7, 0xDB, 0xE7, 0xFF, + 0x30, 0x48, 0x3A, 0x06, 0x0E, + 0x26, 0x29, 0x79, 0x29, 0x26, + 0x40, 0x7F, 0x05, 0x05, 0x07, + 0x40, 0x7F, 0x05, 0x25, 0x3F, + 0x5A, 0x3C, 0xE7, 0x3C, 0x5A, + 0x7F, 0x3E, 0x1C, 0x1C, 0x08, + 0x08, 0x1C, 0x1C, 0x3E, 0x7F, + 0x14, 0x22, 0x7F, 0x22, 0x14, + 0x5F, 0x5F, 0x00, 0x5F, 0x5F, + 0x06, 0x09, 0x7F, 0x01, 0x7F, + 0x00, 0x66, 0x89, 0x95, 0x6A, + 0x60, 0x60, 0x60, 0x60, 0x60, + 0x94, 0xA2, 0xFF, 0xA2, 0x94, + 0x08, 0x04, 0x7E, 0x04, 0x08, + 0x10, 0x20, 0x7E, 0x20, 0x10, + 0x08, 0x08, 0x2A, 0x1C, 0x08, + 0x08, 0x1C, 0x2A, 0x08, 0x08, + 0x1E, 0x10, 0x10, 0x10, 0x10, + 0x0C, 0x1E, 0x0C, 0x1E, 0x0C, + 0x30, 0x38, 0x3E, 0x38, 0x30, + 0x06, 0x0E, 0x3E, 0x0E, 0x06, + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x5F, 0x00, 0x00, + 0x00, 0x07, 0x00, 0x07, 0x00, + 0x14, 0x7F, 0x14, 0x7F, 0x14, + 0x24, 0x2A, 0x7F, 0x2A, 0x12, + 0x23, 0x13, 0x08, 0x64, 0x62, + 0x36, 0x49, 0x56, 0x20, 0x50, + 0x00, 0x08, 0x07, 0x03, 0x00, + 0x00, 0x1C, 0x22, 0x41, 0x00, + 0x00, 0x41, 0x22, 0x1C, 0x00, + 0x2A, 0x1C, 0x7F, 0x1C, 0x2A, + 0x08, 0x08, 0x3E, 0x08, 0x08, + 0x00, 0x80, 0x70, 0x30, 0x00, + 0x08, 0x08, 0x08, 0x08, 0x08, + 0x00, 0x00, 0x60, 0x60, 0x00, + 0x20, 0x10, 0x08, 0x04, 0x02, + 0x3E, 0x51, 0x49, 0x45, 0x3E, + 0x00, 0x42, 0x7F, 0x40, 0x00, + 0x72, 0x49, 0x49, 0x49, 0x46, + 0x21, 0x41, 0x49, 0x4D, 0x33, + 0x18, 0x14, 0x12, 0x7F, 0x10, + 0x27, 0x45, 0x45, 0x45, 0x39, + 0x3C, 0x4A, 0x49, 0x49, 0x31, + 0x41, 0x21, 0x11, 0x09, 0x07, + 0x36, 0x49, 0x49, 0x49, 0x36, + 0x46, 0x49, 0x49, 0x29, 0x1E, + 0x00, 0x00, 0x14, 0x00, 0x00, + 0x00, 0x40, 0x34, 0x00, 0x00, + 0x00, 0x08, 0x14, 0x22, 0x41, + 0x14, 0x14, 0x14, 0x14, 0x14, + 0x00, 0x41, 0x22, 0x14, 0x08, + 0x02, 0x01, 0x59, 0x09, 0x06, + 0x3E, 0x41, 0x5D, 0x59, 0x4E, + 0x7C, 0x12, 0x11, 0x12, 0x7C, + 0x7F, 0x49, 0x49, 0x49, 0x36, + 0x3E, 0x41, 0x41, 0x41, 0x22, + 0x7F, 0x41, 0x41, 0x41, 0x3E, + 0x7F, 0x49, 0x49, 0x49, 0x41, + 0x7F, 0x09, 0x09, 0x09, 0x01, + 0x3E, 0x41, 0x41, 0x51, 0x73, + 0x7F, 0x08, 0x08, 0x08, 0x7F, + 0x00, 0x41, 0x7F, 0x41, 0x00, + 0x20, 0x40, 0x41, 0x3F, 0x01, + 0x7F, 0x08, 0x14, 0x22, 0x41, + 0x7F, 0x40, 0x40, 0x40, 0x40, + 0x7F, 0x02, 0x1C, 0x02, 0x7F, + 0x7F, 0x04, 0x08, 0x10, 0x7F, + 0x3E, 0x41, 0x41, 0x41, 0x3E, + 0x7F, 0x09, 0x09, 0x09, 0x06, + 0x3E, 0x41, 0x51, 0x21, 0x5E, + 0x7F, 0x09, 0x19, 0x29, 0x46, + 0x26, 0x49, 0x49, 0x49, 0x32, + 0x03, 0x01, 0x7F, 0x01, 0x03, + 0x3F, 0x40, 0x40, 0x40, 0x3F, + 0x1F, 0x20, 0x40, 0x20, 0x1F, + 0x3F, 0x40, 0x38, 0x40, 0x3F, + 0x63, 0x14, 0x08, 0x14, 0x63, + 0x03, 0x04, 0x78, 0x04, 0x03, + 0x61, 0x59, 0x49, 0x4D, 0x43, + 0x00, 0x7F, 0x41, 0x41, 0x41, + 0x02, 0x04, 0x08, 0x10, 0x20, + 0x00, 0x41, 0x41, 0x41, 0x7F, + 0x04, 0x02, 0x01, 0x02, 0x04, + 0x40, 0x40, 0x40, 0x40, 0x40, + 0x00, 0x03, 0x07, 0x08, 0x00, + 0x20, 0x54, 0x54, 0x78, 0x40, + 0x7F, 0x28, 0x44, 0x44, 0x38, + 0x38, 0x44, 0x44, 0x44, 0x28, + 0x38, 0x44, 0x44, 0x28, 0x7F, + 0x38, 0x54, 0x54, 0x54, 0x18, + 0x00, 0x08, 0x7E, 0x09, 0x02, + 0x18, 0xA4, 0xA4, 0x9C, 0x78, + 0x7F, 0x08, 0x04, 0x04, 0x78, + 0x00, 0x44, 0x7D, 0x40, 0x00, + 0x20, 0x40, 0x40, 0x3D, 0x00, + 0x7F, 0x10, 0x28, 0x44, 0x00, + 0x00, 0x41, 0x7F, 0x40, 0x00, + 0x7C, 0x04, 0x78, 0x04, 0x78, + 0x7C, 0x08, 0x04, 0x04, 0x78, + 0x38, 0x44, 0x44, 0x44, 0x38, + 0xFC, 0x18, 0x24, 0x24, 0x18, + 0x18, 0x24, 0x24, 0x18, 0xFC, + 0x7C, 0x08, 0x04, 0x04, 0x08, + 0x48, 0x54, 0x54, 0x54, 0x24, + 0x04, 0x04, 0x3F, 0x44, 0x24, + 0x3C, 0x40, 0x40, 0x20, 0x7C, + 0x1C, 0x20, 0x40, 0x20, 0x1C, + 0x3C, 0x40, 0x30, 0x40, 0x3C, + 0x44, 0x28, 0x10, 0x28, 0x44, + 0x4C, 0x90, 0x90, 0x90, 0x7C, + 0x44, 0x64, 0x54, 0x4C, 0x44, + 0x00, 0x08, 0x36, 0x41, 0x00, + 0x00, 0x00, 0x77, 0x00, 0x00, + 0x00, 0x41, 0x36, 0x08, 0x00, + 0x02, 0x01, 0x02, 0x04, 0x02, + 0x3C, 0x26, 0x23, 0x26, 0x3C, + 0x1E, 0xA1, 0xA1, 0x61, 0x12, + 0x3A, 0x40, 0x40, 0x20, 0x7A, + 0x38, 0x54, 0x54, 0x55, 0x59, + 0x21, 0x55, 0x55, 0x79, 0x41, + 0x21, 0x54, 0x54, 0x78, 0x41, + 0x21, 0x55, 0x54, 0x78, 0x40, + 0x20, 0x54, 0x55, 0x79, 0x40, + 0x0C, 0x1E, 0x52, 0x72, 0x12, + 0x39, 0x55, 0x55, 0x55, 0x59, + 0x39, 0x54, 0x54, 0x54, 0x59, + 0x39, 0x55, 0x54, 0x54, 0x58, + 0x00, 0x00, 0x45, 0x7C, 0x41, + 0x00, 0x02, 0x45, 0x7D, 0x42, + 0x00, 0x01, 0x45, 0x7C, 0x40, + 0xF0, 0x29, 0x24, 0x29, 0xF0, + 0xF0, 0x28, 0x25, 0x28, 0xF0, + 0x7C, 0x54, 0x55, 0x45, 0x00, + 0x20, 0x54, 0x54, 0x7C, 0x54, + 0x7C, 0x0A, 0x09, 0x7F, 0x49, + 0x32, 0x49, 0x49, 0x49, 0x32, + 0x32, 0x48, 0x48, 0x48, 0x32, + 0x32, 0x4A, 0x48, 0x48, 0x30, + 0x3A, 0x41, 0x41, 0x21, 0x7A, + 0x3A, 0x42, 0x40, 0x20, 0x78, + 0x00, 0x9D, 0xA0, 0xA0, 0x7D, + 0x39, 0x44, 0x44, 0x44, 0x39, + 0x3D, 0x40, 0x40, 0x40, 0x3D, + 0x3C, 0x24, 0xFF, 0x24, 0x24, + 0x48, 0x7E, 0x49, 0x43, 0x66, + 0x2B, 0x2F, 0xFC, 0x2F, 0x2B, + 0xFF, 0x09, 0x29, 0xF6, 0x20, + 0xC0, 0x88, 0x7E, 0x09, 0x03, + 0x20, 0x54, 0x54, 0x79, 0x41, + 0x00, 0x00, 0x44, 0x7D, 0x41, + 0x30, 0x48, 0x48, 0x4A, 0x32, + 0x38, 0x40, 0x40, 0x22, 0x7A, + 0x00, 0x7A, 0x0A, 0x0A, 0x72, + 0x7D, 0x0D, 0x19, 0x31, 0x7D, + 0x26, 0x29, 0x29, 0x2F, 0x28, + 0x26, 0x29, 0x29, 0x29, 0x26, + 0x30, 0x48, 0x4D, 0x40, 0x20, + 0x38, 0x08, 0x08, 0x08, 0x08, + 0x08, 0x08, 0x08, 0x08, 0x38, + 0x2F, 0x10, 0xC8, 0xAC, 0xBA, + 0x2F, 0x10, 0x28, 0x34, 0xFA, + 0x00, 0x00, 0x7B, 0x00, 0x00, + 0x08, 0x14, 0x2A, 0x14, 0x22, + 0x22, 0x14, 0x2A, 0x14, 0x08, + 0xAA, 0x00, 0x55, 0x00, 0xAA, + 0xAA, 0x55, 0xAA, 0x55, 0xAA, + 0x00, 0x00, 0x00, 0xFF, 0x00, + 0x10, 0x10, 0x10, 0xFF, 0x00, + 0x14, 0x14, 0x14, 0xFF, 0x00, + 0x10, 0x10, 0xFF, 0x00, 0xFF, + 0x10, 0x10, 0xF0, 0x10, 0xF0, + 0x14, 0x14, 0x14, 0xFC, 0x00, + 0x14, 0x14, 0xF7, 0x00, 0xFF, + 0x00, 0x00, 0xFF, 0x00, 0xFF, + 0x14, 0x14, 0xF4, 0x04, 0xFC, + 0x14, 0x14, 0x17, 0x10, 0x1F, + 0x10, 0x10, 0x1F, 0x10, 0x1F, + 0x14, 0x14, 0x14, 0x1F, 0x00, + 0x10, 0x10, 0x10, 0xF0, 0x00, + 0x00, 0x00, 0x00, 0x1F, 0x10, + 0x10, 0x10, 0x10, 0x1F, 0x10, + 0x10, 0x10, 0x10, 0xF0, 0x10, + 0x00, 0x00, 0x00, 0xFF, 0x10, + 0x10, 0x10, 0x10, 0x10, 0x10, + 0x10, 0x10, 0x10, 0xFF, 0x10, + 0x00, 0x00, 0x00, 0xFF, 0x14, + 0x00, 0x00, 0xFF, 0x00, 0xFF, + 0x00, 0x00, 0x1F, 0x10, 0x17, + 0x00, 0x00, 0xFC, 0x04, 0xF4, + 0x14, 0x14, 0x17, 0x10, 0x17, + 0x14, 0x14, 0xF4, 0x04, 0xF4, + 0x00, 0x00, 0xFF, 0x00, 0xF7, + 0x14, 0x14, 0x14, 0x14, 0x14, + 0x14, 0x14, 0xF7, 0x00, 0xF7, + 0x14, 0x14, 0x14, 0x17, 0x14, + 0x10, 0x10, 0x1F, 0x10, 0x1F, + 0x14, 0x14, 0x14, 0xF4, 0x14, + 0x10, 0x10, 0xF0, 0x10, 0xF0, + 0x00, 0x00, 0x1F, 0x10, 0x1F, + 0x00, 0x00, 0x00, 0x1F, 0x14, + 0x00, 0x00, 0x00, 0xFC, 0x14, + 0x00, 0x00, 0xF0, 0x10, 0xF0, + 0x10, 0x10, 0xFF, 0x10, 0xFF, + 0x14, 0x14, 0x14, 0xFF, 0x14, + 0x10, 0x10, 0x10, 0x1F, 0x00, + 0x00, 0x00, 0x00, 0xF0, 0x10, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, + 0xFF, 0xFF, 0xFF, 0x00, 0x00, + 0x00, 0x00, 0x00, 0xFF, 0xFF, + 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, + 0x38, 0x44, 0x44, 0x38, 0x44, + 0x7C, 0x2A, 0x2A, 0x3E, 0x14, + 0x7E, 0x02, 0x02, 0x06, 0x06, + 0x02, 0x7E, 0x02, 0x7E, 0x02, + 0x63, 0x55, 0x49, 0x41, 0x63, + 0x38, 0x44, 0x44, 0x3C, 0x04, + 0x40, 0x7E, 0x20, 0x1E, 0x20, + 0x06, 0x02, 0x7E, 0x02, 0x02, + 0x99, 0xA5, 0xE7, 0xA5, 0x99, + 0x1C, 0x2A, 0x49, 0x2A, 0x1C, + 0x4C, 0x72, 0x01, 0x72, 0x4C, + 0x30, 0x4A, 0x4D, 0x4D, 0x30, + 0x30, 0x48, 0x78, 0x48, 0x30, + 0xBC, 0x62, 0x5A, 0x46, 0x3D, + 0x3E, 0x49, 0x49, 0x49, 0x00, + 0x7E, 0x01, 0x01, 0x01, 0x7E, + 0x2A, 0x2A, 0x2A, 0x2A, 0x2A, + 0x44, 0x44, 0x5F, 0x44, 0x44, + 0x40, 0x51, 0x4A, 0x44, 0x40, + 0x40, 0x44, 0x4A, 0x51, 0x40, + 0x00, 0x00, 0xFF, 0x01, 0x03, + 0xE0, 0x80, 0xFF, 0x00, 0x00, + 0x08, 0x08, 0x6B, 0x6B, 0x08, + 0x36, 0x12, 0x36, 0x24, 0x36, + 0x06, 0x0F, 0x09, 0x0F, 0x06, + 0x00, 0x00, 0x18, 0x18, 0x00, + 0x00, 0x00, 0x10, 0x10, 0x00, + 0x30, 0x40, 0xFF, 0x01, 0x01, + 0x00, 0x1F, 0x01, 0x01, 0x1E, + 0x00, 0x19, 0x1D, 0x17, 0x12, + 0x00, 0x3C, 0x3C, 0x3C, 0x3C, + 0x00, 0x00, 0x00, 0x00, 0x00, +}; +#endif diff --git a/libraries/TFT/utility/keywords.txt b/libraries/TFT/utility/keywords.txt new file mode 100644 index 00000000000..9614847da16 --- /dev/null +++ b/libraries/TFT/utility/keywords.txt @@ -0,0 +1,70 @@ +####################################### +# Syntax Coloring Map For Adafruit_GFX +# and Adafruit_ST7735 +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +Adafruit_GFX KEYWORD1 +Adafruit_ST7735 KEYWORD1 +PImage KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +drawPixel KEYWORD2 +invertDisplay KEYWORD2 +drawLine KEYWORD2 +drawFastVLine KEYWORD2 +drawFastHLine KEYWORD2 +drawRect KEYWORD2 +fillRect KEYWORD2 +fillScreen KEYWORD2 +drawCircle KEYWORD2 +drawCircleHelper KEYWORD2 +fillCircle KEYWORD2 +fillCircleHelper KEYWORD2 +drawTriangle KEYWORD2 +fillTriangle KEYWORD2 +drawRoundRect KEYWORD2 +fillRoundRect KEYWORD2 +drawBitmap KEYWORD2 +drawChar KEYWORD2 +setCursor KEYWORD2 +setTextColor KEYWORD2 +setTextSize KEYWORD2 +setTextWrap KEYWORD2 +height KEYWORD2 +width KEYWORD2 +setRotation KEYWORD2 +getRotation KEYWORD2 + + + +newColor KEYWORD2 +background KEYWORD2 +fill KEYWORD2 +noFill KEYWORD2 +stroke KEYWORD2 +noStroke KEYWORD2 +text KEYWORD2 +textWrap KEYWORD2 +textSize KEYWORD2 +circle KEYWORD2 +point KEYWORD2 +quad KEYWORD2 +rect KEYWORD2 +triangle KEYWORD2 +loadImage KEYWORD2 +image KEYWORD2 + +draw KEYWORD2 +isValid KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### + diff --git a/libraries/WiFi/WiFi.cpp b/libraries/WiFi/WiFi.cpp index f209280fdef..572b4cad210 100755 --- a/libraries/WiFi/WiFi.cpp +++ b/libraries/WiFi/WiFi.cpp @@ -1,3 +1,22 @@ +/* + WiFi.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + #include "wifi_drv.h" #include "WiFi.h" diff --git a/libraries/WiFi/WiFi.h b/libraries/WiFi/WiFi.h index ef36a84a973..0ec09460624 100755 --- a/libraries/WiFi/WiFi.h +++ b/libraries/WiFi/WiFi.h @@ -1,3 +1,22 @@ +/* + WiFi.h - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + #ifndef WiFi_h #define WiFi_h diff --git a/libraries/WiFi/WiFiClient.cpp b/libraries/WiFi/WiFiClient.cpp index 0b4b6dc8af7..6018acc8c1b 100755 --- a/libraries/WiFi/WiFiClient.cpp +++ b/libraries/WiFi/WiFiClient.cpp @@ -1,3 +1,22 @@ +/* + WiFiClient.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + extern "C" { #include "utility/wl_definitions.h" #include "utility/wl_types.h" diff --git a/libraries/WiFi/WiFiClient.h b/libraries/WiFi/WiFiClient.h index 5a7f0f3b831..f2f7fe08ed8 100755 --- a/libraries/WiFi/WiFiClient.h +++ b/libraries/WiFi/WiFiClient.h @@ -1,3 +1,22 @@ +/* + WiFiClient.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + #ifndef wificlient_h #define wificlient_h #include "Arduino.h" diff --git a/libraries/WiFi/WiFiServer.cpp b/libraries/WiFi/WiFiServer.cpp index 2f03bc1c1d2..8e5601cae12 100644 --- a/libraries/WiFi/WiFiServer.cpp +++ b/libraries/WiFi/WiFiServer.cpp @@ -1,3 +1,22 @@ +/* + WiFiServer.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + #include #include "server_drv.h" diff --git a/libraries/WiFi/WiFiServer.h b/libraries/WiFi/WiFiServer.h index 68b574c2980..e872e728ee7 100755 --- a/libraries/WiFi/WiFiServer.h +++ b/libraries/WiFi/WiFiServer.h @@ -1,3 +1,22 @@ +/* + WiFiServer.h - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + #ifndef wifiserver_h #define wifiserver_h diff --git a/libraries/WiFi/WiFiUdp.cpp b/libraries/WiFi/WiFiUdp.cpp index 7020df80b02..ede07999103 100644 --- a/libraries/WiFi/WiFiUdp.cpp +++ b/libraries/WiFi/WiFiUdp.cpp @@ -1,3 +1,21 @@ +/* + WiFiUdp.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ extern "C" { #include "utility/debug.h" diff --git a/libraries/WiFi/WiFiUdp.h b/libraries/WiFi/WiFiUdp.h index 1b316937569..fe6e0255ad8 100644 --- a/libraries/WiFi/WiFiUdp.h +++ b/libraries/WiFi/WiFiUdp.h @@ -1,3 +1,22 @@ +/* + WiFiUdp.h - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + #ifndef wifiudp_h #define wifiudp_h diff --git a/libraries/WiFi/examples/ConnectNoEncryption/ConnectNoEncryption.ino b/libraries/WiFi/examples/ConnectNoEncryption/ConnectNoEncryption.ino index f42a7f37717..2d27392b8aa 100644 --- a/libraries/WiFi/examples/ConnectNoEncryption/ConnectNoEncryption.ino +++ b/libraries/WiFi/examples/ConnectNoEncryption/ConnectNoEncryption.ino @@ -1,38 +1,43 @@ /* - - This example connects to an unencrypted Wifi network. + + This example connects to an unencrypted Wifi network. Then it prints the MAC address of the Wifi shield, the IP address obtained, and other network details. Circuit: * WiFi shield attached - + created 13 July 2010 by dlf (Metodo2 srl) modified 31 May 2012 by Tom Igoe */ - #include +#include +#include char ssid[] = "yourNetwork"; // the name of your network int status = WL_IDLE_STATUS; // the Wifi radio's status void setup() { //Initialize serial and wait for port to open: - Serial.begin(9600); + Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } - + // check for the presence of the shield: if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); + Serial.println("WiFi shield not present"); // don't continue: - while(true); - } - - // attempt to connect to Wifi network: - while ( status != WL_CONNECTED) { + while (true); + } + + String fv = WiFi.firmwareVersion(); + if ( fv != "1.1.0" ) + Serial.println("Please upgrade the firmware"); + + // attempt to connect to Wifi network: + while ( status != WL_CONNECTED) { Serial.print("Attempting to connect to open SSID: "); Serial.println(ssid); status = WiFi.begin(ssid); @@ -40,7 +45,7 @@ void setup() { // wait 10 seconds for connection: delay(10000); } - + // you're connected now, so print out the data: Serial.print("You're connected to the network"); printCurrentNet(); @@ -56,26 +61,26 @@ void loop() { void printWifiData() { // print your WiFi shield's IP address: IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); + Serial.print("IP Address: "); Serial.println(ip); Serial.println(ip); - + // print your MAC address: - byte mac[6]; + byte mac[6]; WiFi.macAddress(mac); Serial.print("MAC address: "); - Serial.print(mac[5],HEX); + Serial.print(mac[5], HEX); Serial.print(":"); - Serial.print(mac[4],HEX); + Serial.print(mac[4], HEX); Serial.print(":"); - Serial.print(mac[3],HEX); + Serial.print(mac[3], HEX); Serial.print(":"); - Serial.print(mac[2],HEX); + Serial.print(mac[2], HEX); Serial.print(":"); - Serial.print(mac[1],HEX); + Serial.print(mac[1], HEX); Serial.print(":"); - Serial.println(mac[0],HEX); - + Serial.println(mac[0], HEX); + // print your subnet mask: IPAddress subnet = WiFi.subnetMask(); Serial.print("NetMask: "); @@ -94,19 +99,19 @@ void printCurrentNet() { // print the MAC address of the router you're attached to: byte bssid[6]; - WiFi.BSSID(bssid); + WiFi.BSSID(bssid); Serial.print("BSSID: "); - Serial.print(bssid[5],HEX); + Serial.print(bssid[5], HEX); Serial.print(":"); - Serial.print(bssid[4],HEX); + Serial.print(bssid[4], HEX); Serial.print(":"); - Serial.print(bssid[3],HEX); + Serial.print(bssid[3], HEX); Serial.print(":"); - Serial.print(bssid[2],HEX); + Serial.print(bssid[2], HEX); Serial.print(":"); - Serial.print(bssid[1],HEX); + Serial.print(bssid[1], HEX); Serial.print(":"); - Serial.println(bssid[0],HEX); + Serial.println(bssid[0], HEX); // print the received signal strength: long rssi = WiFi.RSSI(); @@ -116,6 +121,6 @@ void printCurrentNet() { // print the encryption type: byte encryption = WiFi.encryptionType(); Serial.print("Encryption Type:"); - Serial.println(encryption,HEX); + Serial.println(encryption, HEX); } diff --git a/libraries/WiFi/examples/ConnectWithWEP/ConnectWithWEP.ino b/libraries/WiFi/examples/ConnectWithWEP/ConnectWithWEP.ino index 19736b5b231..0f440ed69c8 100644 --- a/libraries/WiFi/examples/ConnectWithWEP/ConnectWithWEP.ino +++ b/libraries/WiFi/examples/ConnectWithWEP/ConnectWithWEP.ino @@ -1,50 +1,55 @@ /* - - This example connects to a WEP-encrypted Wifi network. + + This example connects to a WEP-encrypted Wifi network. Then it prints the MAC address of the Wifi shield, the IP address obtained, and other network details. - - If you use 40-bit WEP, you need a key that is 10 characters long, - and the characters must be hexadecimal (0-9 or A-F). - e.g. for 40-bit, ABBADEAF01 will work, but ABBADEAF won't work - (too short) and ABBAISDEAF won't work (I and S are not - hexadecimal characters). - - For 128-bit, you need a string that is 26 characters long. - D0D0DEADF00DABBADEAFBEADED will work because it's 26 characters, + + If you use 40-bit WEP, you need a key that is 10 characters long, + and the characters must be hexadecimal (0-9 or A-F). + e.g. for 40-bit, ABBADEAF01 will work, but ABBADEAF won't work + (too short) and ABBAISDEAF won't work (I and S are not + hexadecimal characters). + + For 128-bit, you need a string that is 26 characters long. + D0D0DEADF00DABBADEAFBEADED will work because it's 26 characters, all in the 0-9, A-F range. - + Circuit: * WiFi shield attached - + created 13 July 2010 by dlf (Metodo2 srl) modified 31 May 2012 by Tom Igoe */ +#include #include -char ssid[] = "yourNetwork"; // your network SSID (name) +char ssid[] = "yourNetwork"; // your network SSID (name) char key[] = "D0D0DEADF00DABBADEAFBEADED"; // your network key int keyIndex = 0; // your network key Index number int status = WL_IDLE_STATUS; // the Wifi radio's status void setup() { //Initialize serial and wait for port to open: - Serial.begin(9600); + Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } // check for the presence of the shield: if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); + Serial.println("WiFi shield not present"); // don't continue: - while(true); - } + while (true); + } + + String fv = WiFi.firmwareVersion(); + if ( fv != "1.1.0" ) + Serial.println("Please upgrade the firmware"); // attempt to connect to Wifi network: - while ( status != WL_CONNECTED) { + while ( status != WL_CONNECTED) { Serial.print("Attempting to connect to WEP network, SSID: "); Serial.println(ssid); status = WiFi.begin(ssid, keyIndex, key); @@ -73,20 +78,20 @@ void printWifiData() { Serial.println(ip); // print your MAC address: - byte mac[6]; + byte mac[6]; WiFi.macAddress(mac); Serial.print("MAC address: "); - Serial.print(mac[5],HEX); + Serial.print(mac[5], HEX); Serial.print(":"); - Serial.print(mac[4],HEX); + Serial.print(mac[4], HEX); Serial.print(":"); - Serial.print(mac[3],HEX); + Serial.print(mac[3], HEX); Serial.print(":"); - Serial.print(mac[2],HEX); + Serial.print(mac[2], HEX); Serial.print(":"); - Serial.print(mac[1],HEX); + Serial.print(mac[1], HEX); Serial.print(":"); - Serial.println(mac[0],HEX); + Serial.println(mac[0], HEX); } void printCurrentNet() { @@ -96,19 +101,19 @@ void printCurrentNet() { // print the MAC address of the router you're attached to: byte bssid[6]; - WiFi.BSSID(bssid); + WiFi.BSSID(bssid); Serial.print("BSSID: "); - Serial.print(bssid[5],HEX); + Serial.print(bssid[5], HEX); Serial.print(":"); - Serial.print(bssid[4],HEX); + Serial.print(bssid[4], HEX); Serial.print(":"); - Serial.print(bssid[3],HEX); + Serial.print(bssid[3], HEX); Serial.print(":"); - Serial.print(bssid[2],HEX); + Serial.print(bssid[2], HEX); Serial.print(":"); - Serial.print(bssid[1],HEX); + Serial.print(bssid[1], HEX); Serial.print(":"); - Serial.println(bssid[0],HEX); + Serial.println(bssid[0], HEX); // print the received signal strength: long rssi = WiFi.RSSI(); @@ -118,7 +123,7 @@ void printCurrentNet() { // print the encryption type: byte encryption = WiFi.encryptionType(); Serial.print("Encryption Type:"); - Serial.println(encryption,HEX); + Serial.println(encryption, HEX); Serial.println(); } diff --git a/libraries/WiFi/examples/ConnectWithWPA/ConnectWithWPA.ino b/libraries/WiFi/examples/ConnectWithWPA/ConnectWithWPA.ino index fcc33ecaa0a..aa1b42ca91b 100644 --- a/libraries/WiFi/examples/ConnectWithWPA/ConnectWithWPA.ino +++ b/libraries/WiFi/examples/ConnectWithWPA/ConnectWithWPA.ino @@ -1,48 +1,53 @@ /* - - This example connects to an unencrypted Wifi network. + + This example connects to an unencrypted Wifi network. Then it prints the MAC address of the Wifi shield, the IP address obtained, and other network details. Circuit: * WiFi shield attached - + created 13 July 2010 by dlf (Metodo2 srl) modified 31 May 2012 by Tom Igoe */ - #include +#include +#include -char ssid[] = "yourNetwork"; // your network SSID (name) +char ssid[] = "yourNetwork"; // your network SSID (name) char pass[] = "secretPassword"; // your network password int status = WL_IDLE_STATUS; // the Wifi radio's status void setup() { //Initialize serial and wait for port to open: - Serial.begin(9600); + Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } - + // check for the presence of the shield: if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); + Serial.println("WiFi shield not present"); // don't continue: - while(true); - } - - // attempt to connect to Wifi network: - while ( status != WL_CONNECTED) { + while (true); + } + + String fv = WiFi.firmwareVersion(); + if ( fv != "1.1.0" ) + Serial.println("Please upgrade the firmware"); + + // attempt to connect to Wifi network: + while ( status != WL_CONNECTED) { Serial.print("Attempting to connect to WPA SSID: "); Serial.println(ssid); - // Connect to WPA/WPA2 network: + // Connect to WPA/WPA2 network: status = WiFi.begin(ssid, pass); // wait 10 seconds for connection: delay(10000); } - + // you're connected now, so print out the data: Serial.print("You're connected to the network"); printCurrentNet(); @@ -59,26 +64,26 @@ void loop() { void printWifiData() { // print your WiFi shield's IP address: IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); + Serial.print("IP Address: "); Serial.println(ip); Serial.println(ip); - + // print your MAC address: - byte mac[6]; + byte mac[6]; WiFi.macAddress(mac); Serial.print("MAC address: "); - Serial.print(mac[5],HEX); + Serial.print(mac[5], HEX); Serial.print(":"); - Serial.print(mac[4],HEX); + Serial.print(mac[4], HEX); Serial.print(":"); - Serial.print(mac[3],HEX); + Serial.print(mac[3], HEX); Serial.print(":"); - Serial.print(mac[2],HEX); + Serial.print(mac[2], HEX); Serial.print(":"); - Serial.print(mac[1],HEX); + Serial.print(mac[1], HEX); Serial.print(":"); - Serial.println(mac[0],HEX); - + Serial.println(mac[0], HEX); + } void printCurrentNet() { @@ -88,19 +93,19 @@ void printCurrentNet() { // print the MAC address of the router you're attached to: byte bssid[6]; - WiFi.BSSID(bssid); + WiFi.BSSID(bssid); Serial.print("BSSID: "); - Serial.print(bssid[5],HEX); + Serial.print(bssid[5], HEX); Serial.print(":"); - Serial.print(bssid[4],HEX); + Serial.print(bssid[4], HEX); Serial.print(":"); - Serial.print(bssid[3],HEX); + Serial.print(bssid[3], HEX); Serial.print(":"); - Serial.print(bssid[2],HEX); + Serial.print(bssid[2], HEX); Serial.print(":"); - Serial.print(bssid[1],HEX); + Serial.print(bssid[1], HEX); Serial.print(":"); - Serial.println(bssid[0],HEX); + Serial.println(bssid[0], HEX); // print the received signal strength: long rssi = WiFi.RSSI(); @@ -110,7 +115,7 @@ void printCurrentNet() { // print the encryption type: byte encryption = WiFi.encryptionType(); Serial.print("Encryption Type:"); - Serial.println(encryption,HEX); + Serial.println(encryption, HEX); Serial.println(); } diff --git a/libraries/WiFi/examples/ScanNetworks/ScanNetworks.ino b/libraries/WiFi/examples/ScanNetworks/ScanNetworks.ino index 93b30006efb..8658ef0cb9f 100644 --- a/libraries/WiFi/examples/ScanNetworks/ScanNetworks.ino +++ b/libraries/WiFi/examples/ScanNetworks/ScanNetworks.ino @@ -1,13 +1,13 @@ /* - + This example prints the Wifi shield's MAC address, and scans for available Wifi networks using the Wifi shield. - Every ten seconds, it scans again. It doesn't actually + Every ten seconds, it scans again. It doesn't actually connect to any network, so no encryption scheme is specified. - + Circuit: * WiFi shield attached - + created 13 July 2010 by dlf (Metodo2 srl) modified 21 Junn 2012 @@ -20,17 +20,21 @@ void setup() { //Initialize serial and wait for port to open: - Serial.begin(9600); + Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } // check for the presence of the shield: if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); + Serial.println("WiFi shield not present"); // don't continue: - while(true); - } + while (true); + } + + String fv = WiFi.firmwareVersion(); + if ( fv != "1.1.0" ) + Serial.println("Please upgrade the firmware"); // Print WiFi MAC address: printMacAddress(); @@ -49,22 +53,22 @@ void loop() { void printMacAddress() { // the MAC address of your Wifi shield - byte mac[6]; + byte mac[6]; // print your MAC address: WiFi.macAddress(mac); Serial.print("MAC: "); - Serial.print(mac[5],HEX); + Serial.print(mac[5], HEX); Serial.print(":"); - Serial.print(mac[4],HEX); + Serial.print(mac[4], HEX); Serial.print(":"); - Serial.print(mac[3],HEX); + Serial.print(mac[3], HEX); Serial.print(":"); - Serial.print(mac[2],HEX); + Serial.print(mac[2], HEX); Serial.print(":"); - Serial.print(mac[1],HEX); + Serial.print(mac[1], HEX); Serial.print(":"); - Serial.println(mac[0],HEX); + Serial.println(mac[0], HEX); } void listNetworks() { @@ -72,17 +76,17 @@ void listNetworks() { Serial.println("** Scan Networks **"); int numSsid = WiFi.scanNetworks(); if (numSsid == -1) - { + { Serial.println("Couldn't get a wifi connection"); - while(true); - } + while (true); + } // print the list of networks seen: Serial.print("number of available networks:"); Serial.println(numSsid); // print the network number and name for each network found: - for (int thisNet = 0; thisNet #include -char ssid[] = "yourNetwork"; // your network SSID (name) +char ssid[] = "yourNetwork"; // your network SSID (name) char pass[] = "secretPassword"; // your network password int keyIndex = 0; // your network key Index number (needed only for WEP) @@ -36,20 +36,24 @@ void setup() { // check for the presence of the shield: if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - while(true); // don't continue - } + Serial.println("WiFi shield not present"); + while (true); // don't continue + } + + String fv = WiFi.firmwareVersion(); + if ( fv != "1.1.0" ) + Serial.println("Please upgrade the firmware"); // attempt to connect to Wifi network: - while ( status != WL_CONNECTED) { + while ( status != WL_CONNECTED) { Serial.print("Attempting to connect to Network named: "); Serial.println(ssid); // print the network name (SSID); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: status = WiFi.begin(ssid, pass); // wait 10 seconds for connection: delay(10000); - } + } server.begin(); // start the web server on port 80 printWifiStatus(); // you're connected now, so print out the status } @@ -69,9 +73,9 @@ void loop() { // if the current line is blank, you got two newline characters in a row. // that's the end of the client HTTP request, so send a response: - if (currentLine.length() == 0) { + if (currentLine.length() == 0) { // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK) - // and a content-type so the client knows what's coming, then a blank line: + // and a content-type so the client knows what's coming, then a blank line: client.println("HTTP/1.1 200 OK"); client.println("Content-type:text/html"); client.println(); @@ -83,12 +87,12 @@ void loop() { // The HTTP response ends with another blank line: client.println(); // break out of the while loop: - break; - } + break; + } else { // if you got a newline, then clear currentLine: currentLine = ""; } - } + } else if (c != '\r') { // if you got anything else but a carriage return character, currentLine += c; // add it to the end of the currentLine } diff --git a/libraries/WiFi/examples/WiFiChatServer/WiFiChatServer.ino b/libraries/WiFi/examples/WiFiChatServer/WiFiChatServer.ino index e4b1d1a3b66..b50a38ae0f3 100644 --- a/libraries/WiFi/examples/WiFiChatServer/WiFiChatServer.ino +++ b/libraries/WiFi/examples/WiFiChatServer/WiFiChatServer.ino @@ -1,28 +1,28 @@ /* Chat Server - + A simple server that distributes any incoming messages to all connected clients. To use telnet to your device's IP address and type. You can see the client's input in the serial monitor as well. - - This example is written for a network using WPA encryption. For + + This example is written for a network using WPA encryption. For WEP or WPA, change the Wifi.begin() call accordingly. - - + + Circuit: * WiFi shield attached - + created 18 Dec 2009 by David A. Mellis modified 31 May 2012 by Tom Igoe - + */ #include #include -char ssid[] = "yourNetwork"; // your network SSID (name) +char ssid[] = "yourNetwork"; // your network SSID (name) char pass[] = "secretPassword"; // your network password (use for WPA, or use as key for WEP) int keyIndex = 0; // your network key Index number (needed only for WEP) @@ -35,33 +35,38 @@ boolean alreadyConnected = false; // whether or not the client was connected pre void setup() { //Initialize serial and wait for port to open: - Serial.begin(9600); + Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } - + // check for the presence of the shield: if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); + Serial.println("WiFi shield not present"); // don't continue: - while(true); - } - + while (true); + } + + String fv = WiFi.firmwareVersion(); + if ( fv != "1.1.0" ) + Serial.println("Please upgrade the firmware"); + // attempt to connect to Wifi network: - while ( status != WL_CONNECTED) { + while ( status != WL_CONNECTED) { Serial.print("Attempting to connect to SSID: "); Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: status = WiFi.begin(ssid, pass); // wait 10 seconds for connection: delay(10000); - } + } + // start the server: server.begin(); // you're connected now, so print out the status: printWifiStatus(); - } +} void loop() { @@ -73,11 +78,11 @@ void loop() { if (client) { if (!alreadyConnected) { // clead out the input buffer: - client.flush(); + client.flush(); Serial.println("We have a new client"); - client.println("Hello, client!"); + client.println("Hello, client!"); alreadyConnected = true; - } + } if (client.available() > 0) { // read the bytes incoming from the client: diff --git a/libraries/WiFi/examples/WiFiTwitterClient/WiFiTwitterClient.ino b/libraries/WiFi/examples/WiFiTwitterClient/WiFiTwitterClient.ino deleted file mode 100644 index d500cfb9b27..00000000000 --- a/libraries/WiFi/examples/WiFiTwitterClient/WiFiTwitterClient.ino +++ /dev/null @@ -1,163 +0,0 @@ -/* - Wifi Twitter Client with Strings - - This sketch connects to Twitter using using an Arduino WiFi shield. - It parses the XML returned, and looks for this is a tweet - - This example is written for a network using WPA encryption. For - WEP or WPA, change the Wifi.begin() call accordingly. - - This example uses the String library, which is part of the Arduino core from - version 0019. - - Circuit: - * WiFi shield attached to pins 10, 11, 12, 13 - - created 23 apr 2012 - modified 31 May 2012 - by Tom Igoe - - This code is in the public domain. - - */ -#include -#include - -char ssid[] = "yourNetwork"; // your network SSID (name) -char pass[] = "password"; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number (needed only for WEP) - -int status = WL_IDLE_STATUS; // status of the wifi connection - -// initialize the library instance: -WiFiClient client; - -const unsigned long requestInterval = 30*1000; // delay between requests; 30 seconds - -// if you don't want to use DNS (and reduce your sketch size) -// use the numeric IP instead of the name for the server: -//IPAddress server(199,59,149,200); // numeric IP for api.twitter.com -char server[] = "api.twitter.com"; // name address for twitter API - -boolean requested; // whether you've made a request since connecting -unsigned long lastAttemptTime = 0; // last time you connected to the server, in milliseconds - -String currentLine = ""; // string to hold the text from server -String tweet = ""; // string to hold the tweet -boolean readingTweet = false; // if you're currently reading the tweet - -void setup() { - // reserve space for the strings: - currentLine.reserve(256); - tweet.reserve(150); - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while(true); - } - - // attempt to connect to Wifi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - // you're connected now, so print out the status: - printWifiStatus(); - connectToServer(); -} - -void loop() -{ - if (client.connected()) { - if (client.available()) { - // read incoming bytes: - char inChar = client.read(); - - // add incoming byte to end of line: - currentLine += inChar; - - // if you get a newline, clear the line: - if (inChar == '\n') { - currentLine = ""; - } - // if the current line ends with , it will - // be followed by the tweet: - if ( currentLine.endsWith("")) { - // tweet is beginning. Clear the tweet string: - readingTweet = true; - tweet = ""; - // break out of the loop so this character isn't added to the tweet: - return; - } - // if you're currently reading the bytes of a tweet, - // add them to the tweet String: - if (readingTweet) { - if (inChar != '<') { - tweet += inChar; - } - else { - // if you got a "<" character, - // you've reached the end of the tweet: - readingTweet = false; - Serial.println(tweet); - // close the connection to the server: - client.stop(); - } - } - } - } - else if (millis() - lastAttemptTime > requestInterval) { - // if you're not connected, and two minutes have passed since - // your last connection, then attempt to connect again: - connectToServer(); - } -} - -void connectToServer() { - // attempt to connect, and wait a millisecond: - Serial.println("connecting to server..."); - if (client.connect(server, 80)) { - Serial.println("making HTTP request..."); - // make HTTP GET request to twitter: - client.println("GET /1/statuses/user_timeline.xml?screen_name=arduino HTTP/1.1"); - client.println("Host: api.twitter.com"); - client.println("Connection: close"); - client.println(); - } - // note the time of this connect attempt: - lastAttemptTime = millis(); -} - - -void printWifiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} - - - - diff --git a/libraries/WiFi/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino b/libraries/WiFi/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino index dd8b003fcf5..059b2679dc3 100644 --- a/libraries/WiFi/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino +++ b/libraries/WiFi/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino @@ -1,22 +1,22 @@ /* Udp NTP Client - + Get the time from a Network Time Protocol (NTP) time server - Demonstrates use of UDP sendPacket and ReceivePacket - For more on NTP time servers and the messages needed to communicate with them, + Demonstrates use of UDP sendPacket and ReceivePacket + For more on NTP time servers and the messages needed to communicate with them, see http://en.wikipedia.org/wiki/Network_Time_Protocol - - created 4 Sep 2010 + + created 4 Sep 2010 by Michael Margolis modified 9 Apr 2012 by Tom Igoe - + This code is in the public domain. - + */ -#include +#include #include #include @@ -31,12 +31,12 @@ IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message -byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets +byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets // A UDP instance to let us send and receive packets over UDP WiFiUDP Udp; -void setup() +void setup() { // Open serial communications and wait for port to open: Serial.begin(9600); @@ -46,17 +46,20 @@ void setup() // check for the presence of the shield: if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); + Serial.println("WiFi shield not present"); // don't continue: - while(true); - } + while (true); + } + String fv = WiFi.firmwareVersion(); + if ( fv != "1.1.0" ) + Serial.println("Please upgrade the firmware"); // attempt to connect to Wifi network: - while ( status != WL_CONNECTED) { + while ( status != WL_CONNECTED) { Serial.print("Attempting to connect to SSID: "); Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: status = WiFi.begin(ssid, pass); // wait 10 seconds for connection: @@ -73,61 +76,61 @@ void setup() void loop() { sendNTPpacket(timeServer); // send an NTP packet to a time server - // wait to see if a reply is available - delay(1000); + // wait to see if a reply is available + delay(1000); Serial.println( Udp.parsePacket() ); - if ( Udp.parsePacket() ) { - Serial.println("packet received"); + if ( Udp.parsePacket() ) { + Serial.println("packet received"); // We've received a packet, read the data from it - Udp.read(packetBuffer,NTP_PACKET_SIZE); // read the packet into the buffer + Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer //the timestamp starts at byte 40 of the received packet and is four bytes, // or two words, long. First, esxtract the two words: unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); - unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]); + unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]); // combine the four bytes (two words) into a long integer // this is NTP time (seconds since Jan 1 1900): - unsigned long secsSince1900 = highWord << 16 | lowWord; + unsigned long secsSince1900 = highWord << 16 | lowWord; Serial.print("Seconds since Jan 1 1900 = " ); - Serial.println(secsSince1900); + Serial.println(secsSince1900); // now convert NTP time into everyday time: Serial.print("Unix time = "); // Unix time starts on Jan 1 1970. In seconds, that's 2208988800: - const unsigned long seventyYears = 2208988800UL; + const unsigned long seventyYears = 2208988800UL; // subtract seventy years: - unsigned long epoch = secsSince1900 - seventyYears; + unsigned long epoch = secsSince1900 - seventyYears; // print Unix time: - Serial.println(epoch); + Serial.println(epoch); // print the hour, minute and second: Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT) Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day) - Serial.print(':'); + Serial.print(':'); if ( ((epoch % 3600) / 60) < 10 ) { // In the first 10 minutes of each hour, we'll want a leading '0' Serial.print('0'); } Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute) - Serial.print(':'); + Serial.print(':'); if ( (epoch % 60) < 10 ) { // In the first 10 seconds of each minute, we'll want a leading '0' Serial.print('0'); } - Serial.println(epoch %60); // print the second + Serial.println(epoch % 60); // print the second } // wait ten seconds before asking for the time again - delay(10000); + delay(10000); } -// send an NTP request to the time server at the given address +// send an NTP request to the time server at the given address unsigned long sendNTPpacket(IPAddress& address) { //Serial.println("1"); // set all bytes in the buffer to 0 - memset(packetBuffer, 0, NTP_PACKET_SIZE); + memset(packetBuffer, 0, NTP_PACKET_SIZE); // Initialize values needed to form NTP request // (see URL above for details on the packets) //Serial.println("2"); @@ -136,20 +139,20 @@ unsigned long sendNTPpacket(IPAddress& address) packetBuffer[2] = 6; // Polling Interval packetBuffer[3] = 0xEC; // Peer Clock Precision // 8 bytes of zero for Root Delay & Root Dispersion - packetBuffer[12] = 49; + packetBuffer[12] = 49; packetBuffer[13] = 0x4E; packetBuffer[14] = 49; packetBuffer[15] = 52; - + //Serial.println("3"); // all NTP fields have been given values, now - // you can send a packet requesting a timestamp: + // you can send a packet requesting a timestamp: Udp.beginPacket(address, 123); //NTP requests are to port 123 //Serial.println("4"); - Udp.write(packetBuffer,NTP_PACKET_SIZE); + Udp.write(packetBuffer, NTP_PACKET_SIZE); //Serial.println("5"); - Udp.endPacket(); + Udp.endPacket(); //Serial.println("6"); } diff --git a/libraries/WiFi/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino b/libraries/WiFi/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino index eb112950368..90deef81efd 100644 --- a/libraries/WiFi/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino +++ b/libraries/WiFi/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino @@ -1,13 +1,13 @@ /* WiFi UDP Send and Receive String - + This sketch wait an UDP packet on localPort using a WiFi shield. When a packet is received an Acknowledge packet is sent to the client on port remotePort - + Circuit: * WiFi shield attached - + created 30 December 2012 by dlf (Metodo2 srl) @@ -19,7 +19,7 @@ #include int status = WL_IDLE_STATUS; -char ssid[] = "yourNetwork"; // your network SSID (name) +char ssid[] = "yourNetwork"; // your network SSID (name) char pass[] = "secretPassword"; // your network password (use for WPA, or use as key for WEP) int keyIndex = 0; // your network key Index number (needed only for WEP) @@ -32,42 +32,46 @@ WiFiUDP Udp; void setup() { //Initialize serial and wait for port to open: - Serial.begin(9600); + Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } - + // check for the presence of the shield: if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); + Serial.println("WiFi shield not present"); // don't continue: - while(true); - } - + while (true); + } + + String fv = WiFi.firmwareVersion(); + if ( fv != "1.1.0" ) + Serial.println("Please upgrade the firmware"); + // attempt to connect to Wifi network: - while ( status != WL_CONNECTED) { + while ( status != WL_CONNECTED) { Serial.print("Attempting to connect to SSID: "); Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: status = WiFi.begin(ssid); - + // wait 10 seconds for connection: delay(10000); - } + } Serial.println("Connected to wifi"); printWifiStatus(); - + Serial.println("\nStarting connection to server..."); // if you get a connection, report back via serial: - Udp.begin(localPort); + Udp.begin(localPort); } void loop() { - + // if there's data available, read a packet int packetSize = Udp.parsePacket(); - if(packetSize) - { + if (packetSize) + { Serial.print("Received packet of size "); Serial.println(packetSize); Serial.print("From "); @@ -77,16 +81,16 @@ void loop() { Serial.println(Udp.remotePort()); // read the packet into packetBufffer - int len = Udp.read(packetBuffer,255); - if (len >0) packetBuffer[len]=0; + int len = Udp.read(packetBuffer, 255); + if (len > 0) packetBuffer[len] = 0; Serial.println("Contents:"); Serial.println(packetBuffer); - + // send a reply, to the IP address and port that sent us the packet we received Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); Udp.write(ReplyBuffer); Udp.endPacket(); - } + } } diff --git a/libraries/WiFi/examples/WiFiWebClient/WiFiWebClient.ino b/libraries/WiFi/examples/WiFiWebClient/WiFiWebClient.ino index 310ec46aadf..017b3572ae9 100644 --- a/libraries/WiFi/examples/WiFiWebClient/WiFiWebClient.ino +++ b/libraries/WiFi/examples/WiFiWebClient/WiFiWebClient.ino @@ -1,19 +1,19 @@ /* Web client - + This sketch connects to a website (http://www.google.com) using a WiFi shield. - - This example is written for a network using WPA encryption. For + + This example is written for a network using WPA encryption. For WEP or WPA, change the Wifi.begin() call accordingly. - - This example is written for a network using WPA encryption. For + + This example is written for a network using WPA encryption. For WEP or WPA, change the Wifi.begin() call accordingly. - + Circuit: * WiFi shield attached - + created 13 July 2010 by dlf (Metodo2 srl) modified 31 May 2012 @@ -24,7 +24,7 @@ #include #include -char ssid[] = "yourNetwork"; // your network SSID (name) +char ssid[] = "yourNetwork"; // your network SSID (name) char pass[] = "secretPassword"; // your network password (use for WPA, or use as key for WEP) int keyIndex = 0; // your network key Index number (needed only for WEP) @@ -35,37 +35,41 @@ int status = WL_IDLE_STATUS; char server[] = "www.google.com"; // name address for Google (using DNS) // Initialize the Ethernet client library -// with the IP address and port of the server +// with the IP address and port of the server // that you want to connect to (port 80 is default for HTTP): WiFiClient client; void setup() { //Initialize serial and wait for port to open: - Serial.begin(9600); + Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } - + // check for the presence of the shield: if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); + Serial.println("WiFi shield not present"); // don't continue: - while(true); - } - + while (true); + } + + String fv = WiFi.firmwareVersion(); + if ( fv != "1.1.0" ) + Serial.println("Please upgrade the firmware"); + // attempt to connect to Wifi network: - while (status != WL_CONNECTED) { + while (status != WL_CONNECTED) { Serial.print("Attempting to connect to SSID: "); Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: status = WiFi.begin(ssid, pass); - + // wait 10 seconds for connection: delay(10000); - } + } Serial.println("Connected to wifi"); printWifiStatus(); - + Serial.println("\nStarting connection to server..."); // if you get a connection, report back via serial: if (client.connect(server, 80)) { @@ -79,7 +83,7 @@ void setup() { } void loop() { - // if there are incoming bytes available + // if there are incoming bytes available // from the server, read them and print them: while (client.available()) { char c = client.read(); @@ -93,7 +97,7 @@ void loop() { client.stop(); // do nothing forevermore: - while(true); + while (true); } } diff --git a/libraries/WiFi/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino b/libraries/WiFi/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino index 96eb6283d87..60f9eb8290b 100644 --- a/libraries/WiFi/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino +++ b/libraries/WiFi/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino @@ -1,24 +1,26 @@ /* - Repeating Wifi Web client - + Repeating Wifi Web Client + This sketch connects to a a web server and makes a request using an Arduino Wifi shield. - + Circuit: - * Wifi shield attached to pins 10, 11, 12, 13 - + * WiFi shield attached to pins SPI pins and pin 7 + created 23 April 2012 - modifide 31 May 2012 + modified 31 May 2012 by Tom Igoe - + modified 13 Jan 2014 + by Federico Vanzati + http://arduino.cc/en/Tutorial/WifiWebClientRepeating This code is in the public domain. */ #include #include - -char ssid[] = "yourNetwork"; // your network SSID (name) + +char ssid[] = "yourNetwork"; // your network SSID (name) char pass[] = "secretPassword"; // your network password int keyIndex = 0; // your network key Index number (needed only for WEP) @@ -31,34 +33,37 @@ WiFiClient client; char server[] = "www.arduino.cc"; //IPAddress server(64,131,82,241); -unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds -boolean lastConnected = false; // state of the connection last time through the main loop -const unsigned long postingInterval = 10*1000; // delay between updates, in milliseconds +unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds +const unsigned long postingInterval = 10L * 1000L; // delay between updates, in milliseconds void setup() { //Initialize serial and wait for port to open: - Serial.begin(9600); + Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } - + // check for the presence of the shield: if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); + Serial.println("WiFi shield not present"); // don't continue: - while(true); - } - + while (true); + } + + String fv = WiFi.firmwareVersion(); + if ( fv != "1.1.0" ) + Serial.println("Please upgrade the firmware"); + // attempt to connect to Wifi network: - while ( status != WL_CONNECTED) { + while ( status != WL_CONNECTED) { Serial.print("Attempting to connect to SSID: "); Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: status = WiFi.begin(ssid, pass); // wait 10 seconds for connection: delay(10000); - } + } // you're connected now, so print out the status: printWifiStatus(); } @@ -72,44 +77,36 @@ void loop() { Serial.write(c); } - // if there's no net connection, but there was one last time - // through the loop, then stop the client: - if (!client.connected() && lastConnected) { - Serial.println(); - Serial.println("disconnecting."); - client.stop(); - } - - // if you're not connected, and ten seconds have passed since - // your last connection, then connect again and send data: - if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) { + // if ten seconds have passed since your last connection, + // then connect again and send data: + if (millis() - lastConnectionTime > postingInterval) { httpRequest(); } - // store the state of the connection for next time through - // the loop: - lastConnected = client.connected(); + } // this method makes a HTTP connection to the server: void httpRequest() { + // close any connection before send a new request. + // This will free the socket on the WiFi shield + client.stop(); + // if there's a successful connection: if (client.connect(server, 80)) { Serial.println("connecting..."); // send the HTTP PUT request: client.println("GET /latest.txt HTTP/1.1"); client.println("Host: www.arduino.cc"); - client.println("User-Agent: arduino-ethernet"); + client.println("User-Agent: ArduinoWiFi/1.1"); client.println("Connection: close"); client.println(); // note the time that the connection was made: lastConnectionTime = millis(); - } + } else { // if you couldn't make a connection: Serial.println("connection failed"); - Serial.println("disconnecting."); - client.stop(); } } @@ -132,7 +129,3 @@ void printWifiStatus() { } - - - - diff --git a/libraries/WiFi/examples/WiFiWebServer/WiFiWebServer.ino b/libraries/WiFi/examples/WiFiWebServer/WiFiWebServer.ino index 7d7a2471328..4ea045683d1 100644 --- a/libraries/WiFi/examples/WiFiWebServer/WiFiWebServer.ino +++ b/libraries/WiFi/examples/WiFiWebServer/WiFiWebServer.ino @@ -1,16 +1,16 @@ /* WiFi Web Server - + A simple web server that shows the value of the analog input pins. using a WiFi shield. - - This example is written for a network using WPA encryption. For + + This example is written for a network using WPA encryption. For WEP or WPA, change the Wifi.begin() call accordingly. - + Circuit: * WiFi shield attached * Analog inputs attached to pins A0 through A5 (optional) - + created 13 July 2010 by dlf (Metodo2 srl) modified 31 May 2012 @@ -22,7 +22,7 @@ #include -char ssid[] = "yourNetwork"; // your network SSID (name) +char ssid[] = "yourNetwork"; // your network SSID (name) char pass[] = "secretPassword"; // your network password int keyIndex = 0; // your network key Index number (needed only for WEP) @@ -32,28 +32,32 @@ WiFiServer server(80); void setup() { //Initialize serial and wait for port to open: - Serial.begin(9600); + Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } - + // check for the presence of the shield: if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); + Serial.println("WiFi shield not present"); // don't continue: - while(true); - } - + while (true); + } + + String fv = WiFi.firmwareVersion(); + if ( fv != "1.1.0" ) + Serial.println("Please upgrade the firmware"); + // attempt to connect to Wifi network: - while ( status != WL_CONNECTED) { + while ( status != WL_CONNECTED) { Serial.print("Attempting to connect to SSID: "); Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: status = WiFi.begin(ssid, pass); // wait 10 seconds for connection: delay(10000); - } + } server.begin(); // you're connected now, so print out the status: printWifiStatus(); @@ -78,12 +82,11 @@ void loop() { // send a standard http response header client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); - client.println("Connection: close"); + client.println("Connection: close"); // the connection will be closed after completion of the response + client.println("Refresh: 5"); // refresh the page automatically every 5 sec client.println(); client.println(""); client.println(""); - // add a meta refresh tag, so the browser pulls again every 5 seconds: - client.println(""); // output the value of each analog input pin for (int analogChannel = 0; analogChannel < 6; analogChannel++) { int sensorReading = analogRead(analogChannel); @@ -91,15 +94,15 @@ void loop() { client.print(analogChannel); client.print(" is "); client.print(sensorReading); - client.println("
"); + client.println("
"); } client.println(""); - break; + break; } if (c == '\n') { // you're starting a new line currentLineIsBlank = true; - } + } else if (c != '\r') { // you've gotten a character on the current line currentLineIsBlank = false; @@ -108,9 +111,10 @@ void loop() { } // give the web browser time to receive the data delay(1); - // close the connection: - client.stop(); - Serial.println("client disonnected"); + + // close the connection: + client.stop(); + Serial.println("client disonnected"); } } diff --git a/libraries/WiFi/examples/WiFiPachubeClient/WiFiPachubeClient.ino b/libraries/WiFi/examples/WiFiXivelyClient/WiFiXivelyClient.ino similarity index 81% rename from libraries/WiFi/examples/WiFiPachubeClient/WiFiPachubeClient.ino rename to libraries/WiFi/examples/WiFiXivelyClient/WiFiXivelyClient.ino index f8ffc074503..b88dd2c584d 100644 --- a/libraries/WiFi/examples/WiFiPachubeClient/WiFiPachubeClient.ino +++ b/libraries/WiFi/examples/WiFiXivelyClient/WiFiXivelyClient.ino @@ -1,37 +1,37 @@ /* - Wifi Pachube sensor client + Wifi Xively sensor client - This sketch connects an analog sensor to Pachube (http://www.pachube.com) + This sketch connects an analog sensor to Xively (http://www.xively.com) using an Arduino Wifi shield. - - This example is written for a network using WPA encryption. For + + This example is written for a network using WPA encryption. For WEP or WPA, change the Wifi.begin() call accordingly. - This example has been updated to use version 2.0 of the Pachube API. + This example has been updated to use version 2.0 of the Xively API. To make it work, create a feed with a datastream, and give it the ID sensor1. Or change the code below to match your feed. - + Circuit: * Analog sensor attached to analog in 0 * Wifi shield attached to pins 10, 11, 12, 13 - + created 13 Mar 2012 modified 31 May 2012 by Tom Igoe - modified 8 Sept 2012 + modified 8 Nov 2013 by Scott Fitzgerald - + This code is in the public domain. - + */ #include #include -#define APIKEY "YOUR API KEY GOES HERE" // replace your pachube api key here +#define APIKEY "YOUR API KEY GOES HERE" // replace your xively api key here #define FEEDID 00000 // replace your feed ID #define USERAGENT "My Arduino Project" // user agent is the project name -char ssid[] = "yourNetwork"; // your network SSID (name) +char ssid[] = "yourNetwork"; // your network SSID (name) char pass[] = "secretPassword"; // your network password int status = WL_IDLE_STATUS; @@ -40,37 +40,41 @@ int status = WL_IDLE_STATUS; WiFiClient client; // if you don't want to use DNS (and reduce your sketch size) // use the numeric IP instead of the name for the server: -IPAddress server(216,52,233,121); // numeric IP for api.pachube.com -//char server[] = "api.pachube.com"; // name address for pachube API +IPAddress server(216,52,233,121); // numeric IP for api.xively.com +//char server[] = "api.xively.com"; // name address for xively API unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds boolean lastConnected = false; // state of the connection last time through the main loop -const unsigned long postingInterval = 10*1000; //delay between updates to pachube.com +const unsigned long postingInterval = 10*1000; //delay between updates to xively.com void setup() { //Initialize serial and wait for port to open: - Serial.begin(9600); + Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } - + // check for the presence of the shield: if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); + Serial.println("WiFi shield not present"); // don't continue: - while(true); - } - + while (true); + } + + String fv = WiFi.firmwareVersion(); + if ( fv != "1.1.0" ) + Serial.println("Please upgrade the firmware"); + // attempt to connect to Wifi network: - while ( status != WL_CONNECTED) { + while ( status != WL_CONNECTED) { Serial.print("Attempting to connect to SSID: "); Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: status = WiFi.begin(ssid, pass); // wait 10 seconds for connection: delay(10000); - } + } // you're connected now, so print out the status: printWifiStatus(); } @@ -78,7 +82,7 @@ void setup() { void loop() { // read the analog sensor: - int sensorReading = analogRead(A0); + int sensorReading = analogRead(A0); // if there's incoming data from the net connection. // send it out the serial port. This is for debugging @@ -98,7 +102,7 @@ void loop() { // if you're not connected, and ten seconds have passed since // your last connection, then connect again and send data: - if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) { + if (!client.connected() && (millis() - lastConnectionTime > postingInterval)) { sendData(sensorReading); } // store the state of the connection for next time through @@ -115,7 +119,7 @@ void sendData(int thisData) { client.print("PUT /v2/feeds/"); client.print(FEEDID); client.println(".csv HTTP/1.1"); - client.println("Host: api.pachube.com"); + client.println("Host: api.xively.com"); client.print("X-ApiKey: "); client.println(APIKEY); client.print("User-Agent: "); @@ -135,8 +139,8 @@ void sendData(int thisData) { // here's the actual content of the PUT request: client.print("sensor1,"); client.println(thisData); - - } + + } else { // if you couldn't make a connection: Serial.println("connection failed"); @@ -144,7 +148,7 @@ void sendData(int thisData) { Serial.println("disconnecting."); client.stop(); } - // note the time that the connection was made or attempted: + // note the time that the connection was made or attempted: lastConnectionTime = millis(); } @@ -157,12 +161,12 @@ void sendData(int thisData) { int getLength(int someValue) { // there's at least one byte: int digits = 1; - // continually divide the value by ten, + // continually divide the value by ten, // adding one to the digit count for each // time you divide, until you're at 0: - int dividend = someValue /10; + int dividend = someValue / 10; while (dividend > 0) { - dividend = dividend /10; + dividend = dividend / 10; digits++; } // return the number of digits: diff --git a/libraries/WiFi/examples/WiFiPachubeClientString/WiFiPachubeClientString.ino b/libraries/WiFi/examples/WiFiXivelyClientString/WiFiXivelyClientString.ino similarity index 81% rename from libraries/WiFi/examples/WiFiPachubeClientString/WiFiPachubeClientString.ino rename to libraries/WiFi/examples/WiFiXivelyClientString/WiFiXivelyClientString.ino index 243fe838397..20be0feb349 100644 --- a/libraries/WiFi/examples/WiFiPachubeClientString/WiFiPachubeClientString.ino +++ b/libraries/WiFi/examples/WiFiXivelyClientString/WiFiXivelyClientString.ino @@ -1,41 +1,41 @@ /* - Wifi Pachube sensor client with Strings + Wifi Xively sensor client with Strings - This sketch connects an analog sensor to Pachube (http://www.pachube.com) + This sketch connects an analog sensor to Xively (http://www.xively.com) using a Arduino Wifi shield. - - This example is written for a network using WPA encryption. For + + This example is written for a network using WPA encryption. For WEP or WPA, change the Wifi.begin() call accordingly. - This example has been updated to use version 2.0 of the pachube.com API. + This example has been updated to use version 2.0 of the xively.com API. To make it work, create a feed with a datastream, and give it the ID sensor1. Or change the code below to match your feed. - + This example uses the String library, which is part of the Arduino core from - version 0019. - + version 0019. + Circuit: * Analog sensor attached to analog in 0 * Wifi shield attached to pins 10, 11, 12, 13 - + created 16 Mar 2012 modified 31 May 2012 by Tom Igoe modified 8 Sept 2012 by Scott Fitzgerald - + This code is in the public domain. - + */ #include #include -#define APIKEY "YOUR API KEY GOES HERE" // replace your pachube api key here +#define APIKEY "YOUR API KEY GOES HERE" // replace your xively api key here #define FEEDID 00000 // replace your feed ID #define USERAGENT "My Arduino Project" // user agent is the project name -char ssid[] = "yourNetwork"; // your network SSID (name) +char ssid[] = "yourNetwork"; // your network SSID (name) char pass[] = "secretPassword"; // your network password int status = WL_IDLE_STATUS; @@ -45,51 +45,55 @@ WiFiClient client; // if you don't want to use DNS (and reduce your sketch size) // use the numeric IP instead of the name for the server: -//IPAddress server(216,52,233,121); // numeric IP for api.pachube.com -char server[] = "api.pachube.com"; // name address for pachube API +//IPAddress server(216,52,233,121); // numeric IP for api.xively.com +char server[] = "api.xively.com"; // name address for xively API unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds boolean lastConnected = false; // state of the connection last time through the main loop -const unsigned long postingInterval = 10*1000; //delay between updates to pachube.com +const unsigned long postingInterval = 10*1000; //delay between updates to xively.com void setup() { //Initialize serial and wait for port to open: - Serial.begin(9600); + Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } - + // check for the presence of the shield: if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); + Serial.println("WiFi shield not present"); // don't continue: - while(true); - } - + while (true); + } + + String fv = WiFi.firmwareVersion(); + if ( fv != "1.1.0" ) + Serial.println("Please upgrade the firmware"); + // attempt to connect to Wifi network: - while ( status != WL_CONNECTED) { + while ( status != WL_CONNECTED) { Serial.print("Attempting to connect to SSID: "); Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: status = WiFi.begin(ssid, pass); // wait 10 seconds for connection: delay(10000); - } + } // you're connected now, so print out the status: printWifiStatus(); } void loop() { // read the analog sensor: - int sensorReading = analogRead(A0); + int sensorReading = analogRead(A0); // convert the data to a String to send it: String dataString = "sensor1,"; dataString += sensorReading; // you can append multiple readings to this String if your - // pachube feed is set up to handle multiple values: + // xively feed is set up to handle multiple values: int otherSensorReading = analogRead(A1); dataString += "\nsensor2,"; dataString += otherSensorReading; @@ -111,8 +115,8 @@ void loop() { } // if you're not connected, and ten seconds have passed since - // your last connection, then connect again and send data: - if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) { + // your last connection, then connect again and send data: + if (!client.connected() && (millis() - lastConnectionTime > postingInterval)) { sendData(dataString); } // store the state of the connection for next time through @@ -129,7 +133,7 @@ void sendData(String thisData) { client.print("PUT /v2/feeds/"); client.print(FEEDID); client.println(".csv HTTP/1.1"); - client.println("Host: api.pachube.com"); + client.println("Host: api.xively.com"); client.print("X-ApiKey: "); client.println(APIKEY); client.print("User-Agent: "); @@ -144,7 +148,7 @@ void sendData(String thisData) { // here's the actual content of the PUT request: client.println(thisData); - } + } else { // if you couldn't make a connection: Serial.println("connection failed"); diff --git a/libraries/WiFi/utility/debug.h b/libraries/WiFi/utility/debug.h index 9f71055b2e8..5569e45d9e9 100644 --- a/libraries/WiFi/utility/debug.h +++ b/libraries/WiFi/utility/debug.h @@ -1,3 +1,21 @@ +/* + debug.h - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ //*********************************************/ // // File: debug.h diff --git a/libraries/WiFi/utility/server_drv.cpp b/libraries/WiFi/utility/server_drv.cpp index 4a6d2932ba5..e0786ffbd23 100644 --- a/libraries/WiFi/utility/server_drv.cpp +++ b/libraries/WiFi/utility/server_drv.cpp @@ -1,3 +1,22 @@ +/* + server_drv.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + //#define _DEBUG_ #include "server_drv.h" diff --git a/libraries/WiFi/utility/server_drv.h b/libraries/WiFi/utility/server_drv.h index 50ba7e3969e..df9cafb4e83 100644 --- a/libraries/WiFi/utility/server_drv.h +++ b/libraries/WiFi/utility/server_drv.h @@ -1,3 +1,22 @@ +/* + server_drv.h - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + #ifndef Server_Drv_h #define Server_Drv_h diff --git a/libraries/WiFi/utility/socket.c b/libraries/WiFi/utility/socket.c index 665073b04de..11e9b3076a4 100644 --- a/libraries/WiFi/utility/socket.c +++ b/libraries/WiFi/utility/socket.c @@ -1,3 +1,22 @@ +/* + socket.c - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + /* * @file socket.c diff --git a/libraries/WiFi/utility/socket.h b/libraries/WiFi/utility/socket.h index 9b06d00d155..e61b9520077 100644 --- a/libraries/WiFi/utility/socket.h +++ b/libraries/WiFi/utility/socket.h @@ -1,3 +1,22 @@ +/* + socket.h - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + /* * @file socket.h diff --git a/libraries/WiFi/utility/spi_drv.cpp b/libraries/WiFi/utility/spi_drv.cpp index 12a320b0d58..9d8a08569e1 100644 --- a/libraries/WiFi/utility/spi_drv.cpp +++ b/libraries/WiFi/utility/spi_drv.cpp @@ -1,3 +1,21 @@ +/* + spi_drv.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ #include "Arduino.h" #include "spi_drv.h" diff --git a/libraries/WiFi/utility/spi_drv.h b/libraries/WiFi/utility/spi_drv.h index b7e4cb72efb..f56d34ab2aa 100644 --- a/libraries/WiFi/utility/spi_drv.h +++ b/libraries/WiFi/utility/spi_drv.h @@ -1,3 +1,22 @@ +/* + spi_drv.h - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + #ifndef SPI_Drv_h #define SPI_Drv_h diff --git a/libraries/WiFi/utility/wifi_drv.cpp b/libraries/WiFi/utility/wifi_drv.cpp index ccd5f254ffd..685dc937eaa 100644 --- a/libraries/WiFi/utility/wifi_drv.cpp +++ b/libraries/WiFi/utility/wifi_drv.cpp @@ -1,3 +1,22 @@ +/* + wifi_drv.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + #include #include #include diff --git a/libraries/WiFi/utility/wifi_drv.h b/libraries/WiFi/utility/wifi_drv.h index d6ec029ded9..d2429792c5e 100644 --- a/libraries/WiFi/utility/wifi_drv.h +++ b/libraries/WiFi/utility/wifi_drv.h @@ -1,3 +1,22 @@ +/* + wifi_drv.h - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + #ifndef WiFi_Drv_h #define WiFi_Drv_h diff --git a/libraries/WiFi/utility/wifi_spi.h b/libraries/WiFi/utility/wifi_spi.h index 8856e33e93f..4eedcbbd51f 100644 --- a/libraries/WiFi/utility/wifi_spi.h +++ b/libraries/WiFi/utility/wifi_spi.h @@ -1,3 +1,22 @@ +/* + wifi_spi.h - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + #ifndef WiFi_Spi_h #define WiFi_Spi_h diff --git a/libraries/WiFi/utility/wl_definitions.h b/libraries/WiFi/utility/wl_definitions.h index 1ec8e712c7e..b0688604c5d 100644 --- a/libraries/WiFi/utility/wl_definitions.h +++ b/libraries/WiFi/utility/wl_definitions.h @@ -1,3 +1,21 @@ +/* + wl_definitions.h - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ /* * wl_definitions.h * diff --git a/libraries/WiFi/utility/wl_types.h b/libraries/WiFi/utility/wl_types.h index 82b309d7f96..b9fd5fa0a1e 100644 --- a/libraries/WiFi/utility/wl_types.h +++ b/libraries/WiFi/utility/wl_types.h @@ -1,3 +1,21 @@ +/* + wl_types.h - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ /* * wl_types.h * diff --git a/readme.txt b/readme.txt deleted file mode 100644 index 0346ae46ffd..00000000000 --- a/readme.txt +++ /dev/null @@ -1,32 +0,0 @@ -Arduino is an open-source physical computing platform based on a simple i/o -board and a development environment that implements the Processing/Wiring -language. Arduino can be used to develop stand-alone interactive objects or -can be connected to software on your computer (e.g. Flash, Processing, MaxMSP). -The boards can be assembled by hand or purchased preassembled; the open-source -IDE can be downloaded for free. - -For more information, see the website at: http://www.arduino.cc/ -or the forums at: http://arduino.cc/forum/ - -To report a bug in the software, go to: -http://github.com/arduino/Arduino/issues - -For other suggestions, use the forum: -http://arduino.cc/forum/index.php/board,21.0.html - -INSTALLATION -Detailed instructions are in reference/Guide_Windows.html and -reference/Guide_MacOSX.html. For Linux, see the Arduino playground: -http://www.arduino.cc/playground/Learning/Linux - -CREDITS -Arduino is an open source project, supported by many. - -The Arduino team is composed of Massimo Banzi, David Cuartielles, Tom Igoe, -Gianluca Martino, Daniela Antonietti, and David A. Mellis. - -Arduino uses the GNU avr-gcc toolchain, avrdude, avr-libc, and code from -Processing and Wiring. - -Icon and about image designed by ToDo: http://www.todo.to.it/ -