From 86441e434156034404a4126aa1fcc2ee2732bb5a Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Thu, 28 Dec 2017 00:02:19 +0100 Subject: [PATCH] Added first tests for library manager engine --- .../contributions/ContributionsSelfCheck.java | 18 +- .../filters/UpdatableLibraryPredicate.java | 13 +- .../contributions/UpdatableLibraryTest.java | 82 ++ .../libraries/Bridge_1.6.3/Bridge/README.adoc | 24 + .../Bridge/examples/Bridge/Bridge.ino | 183 +++ .../ConsoleAsciiTable/ConsoleAsciiTable.ino | 95 ++ .../examples/ConsolePixel/ConsolePixel.ino | 63 + .../examples/ConsoleRead/ConsoleRead.ino | 58 + .../Bridge/examples/Datalogger/Datalogger.ino | 102 ++ .../FileWriteScript/FileWriteScript.ino | 83 ++ .../Bridge/examples/HttpClient/HttpClient.ino | 51 + .../HttpClientConsole/HttpClientConsole.ino | 53 + .../MailboxReadMessage/MailboxReadMessage.ino | 58 + .../Bridge/examples/Process/Process.ino | 71 + .../RemoteDueBlink/RemoteDueBlink.ino | 33 + .../examples/ShellCommands/ShellCommands.ino | 52 + .../TemperatureWebPanel.ino | 122 ++ .../TemperatureWebPanel/www/index.html | 16 + .../TemperatureWebPanel/www/zepto.min.js | 2 + .../Bridge/examples/TimeCheck/TimeCheck.ino | 88 ++ .../Bridge/examples/WiFiStatus/WiFiStatus.ino | 51 + .../YunFirstConfig/YunFirstConfig.ino | 328 +++++ .../YunSerialTerminal/YunSerialTerminal.ino | 82 ++ .../Bridge_1.6.3/Bridge/keywords.txt | 92 ++ .../Bridge_1.6.3/Bridge/library.properties | 10 + .../Bridge_1.6.3/Bridge/src/Bridge.cpp | 281 ++++ .../Bridge_1.6.3/Bridge/src/Bridge.h | 125 ++ .../Bridge_1.6.3/Bridge/src/BridgeClient.cpp | 207 +++ .../Bridge_1.6.3/Bridge/src/BridgeClient.h | 71 + .../Bridge/src/BridgeSSLClient.cpp | 36 + .../Bridge_1.6.3/Bridge/src/BridgeSSLClient.h | 36 + .../Bridge_1.6.3/Bridge/src/BridgeServer.cpp | 54 + .../Bridge_1.6.3/Bridge/src/BridgeServer.h | 51 + .../Bridge_1.6.3/Bridge/src/BridgeUdp.cpp | 198 +++ .../Bridge_1.6.3/Bridge/src/BridgeUdp.h | 65 + .../Bridge_1.6.3/Bridge/src/Console.cpp | 150 ++ .../Bridge_1.6.3/Bridge/src/Console.h | 71 + .../Bridge_1.6.3/Bridge/src/FileIO.cpp | 283 ++++ .../Bridge_1.6.3/Bridge/src/FileIO.h | 120 ++ .../Bridge_1.6.3/Bridge/src/HttpClient.cpp | 204 +++ .../Bridge_1.6.3/Bridge/src/HttpClient.h | 59 + .../Bridge_1.6.3/Bridge/src/Mailbox.cpp | 56 + .../Bridge_1.6.3/Bridge/src/Mailbox.h | 53 + .../Bridge_1.6.3/Bridge/src/Process.cpp | 142 ++ .../Bridge_1.6.3/Bridge/src/Process.h | 71 + .../Bridge_1.6.3/Bridge/src/YunClient.h | 27 + .../Bridge_1.6.3/Bridge/src/YunServer.h | 27 + .../libraries/Bridge_1.7.0/Bridge/README.adoc | 24 + .../Bridge/examples/Bridge/Bridge.ino | 183 +++ .../ConsoleAsciiTable/ConsoleAsciiTable.ino | 95 ++ .../examples/ConsolePixel/ConsolePixel.ino | 63 + .../examples/ConsoleRead/ConsoleRead.ino | 58 + .../Bridge/examples/Datalogger/Datalogger.ino | 102 ++ .../FileWriteScript/FileWriteScript.ino | 83 ++ .../Bridge/examples/HttpClient/HttpClient.ino | 51 + .../HttpClientConsole/HttpClientConsole.ino | 53 + .../MailboxReadMessage/MailboxReadMessage.ino | 58 + .../Bridge/examples/Process/Process.ino | 71 + .../RemoteDueBlink/RemoteDueBlink.ino | 33 + .../examples/ShellCommands/ShellCommands.ino | 52 + .../TemperatureWebPanel.ino | 122 ++ .../TemperatureWebPanel/www/index.html | 16 + .../TemperatureWebPanel/www/zepto.min.js | 2 + .../Bridge/examples/TimeCheck/TimeCheck.ino | 88 ++ .../Bridge/examples/WiFiStatus/WiFiStatus.ino | 51 + .../YunFirstConfig/YunFirstConfig.ino | 328 +++++ .../YunSerialTerminal/YunSerialTerminal.ino | 82 ++ .../Bridge_1.7.0/Bridge/keywords.txt | 92 ++ .../Bridge_1.7.0/Bridge/library.properties | 10 + .../Bridge_1.7.0/Bridge/src/Bridge.cpp | 312 ++++ .../Bridge_1.7.0/Bridge/src/Bridge.h | 131 ++ .../Bridge_1.7.0/Bridge/src/BridgeClient.cpp | 207 +++ .../Bridge_1.7.0/Bridge/src/BridgeClient.h | 71 + .../Bridge/src/BridgeSSLClient.cpp | 36 + .../Bridge_1.7.0/Bridge/src/BridgeSSLClient.h | 36 + .../Bridge_1.7.0/Bridge/src/BridgeServer.cpp | 54 + .../Bridge_1.7.0/Bridge/src/BridgeServer.h | 51 + .../Bridge_1.7.0/Bridge/src/BridgeUdp.cpp | 198 +++ .../Bridge_1.7.0/Bridge/src/BridgeUdp.h | 65 + .../Bridge_1.7.0/Bridge/src/Console.cpp | 150 ++ .../Bridge_1.7.0/Bridge/src/Console.h | 71 + .../Bridge_1.7.0/Bridge/src/FileIO.cpp | 283 ++++ .../Bridge_1.7.0/Bridge/src/FileIO.h | 120 ++ .../Bridge_1.7.0/Bridge/src/HttpClient.cpp | 204 +++ .../Bridge_1.7.0/Bridge/src/HttpClient.h | 59 + .../Bridge_1.7.0/Bridge/src/Mailbox.cpp | 56 + .../Bridge_1.7.0/Bridge/src/Mailbox.h | 53 + .../Bridge_1.7.0/Bridge/src/Process.cpp | 142 ++ .../Bridge_1.7.0/Bridge/src/Process.h | 71 + .../Bridge_1.7.0/Bridge/src/YunClient.h | 27 + .../Bridge_1.7.0/Bridge/src/YunServer.h | 27 + .../libraries/SD_1.1.1/SD/README.adoc | 24 + .../SD/examples/CardInfo/CardInfo.ino | 112 ++ .../SD/examples/Datalogger/Datalogger.ino | 84 ++ .../SD/examples/DumpFile/DumpFile.ino | 65 + .../SD_1.1.1/SD/examples/Files/Files.ino | 75 + .../SD/examples/ReadWrite/ReadWrite.ino | 79 ++ .../SD/examples/listfiles/listfiles.ino | 80 ++ .../libraries/SD_1.1.1/SD/keywords.txt | 31 + .../libraries/SD_1.1.1/SD/library.properties | 9 + .../libraries/SD_1.1.1/SD/src/File.cpp | 146 ++ .../libraries/SD_1.1.1/SD/src/README.txt | 13 + app/testdata/libraries/SD_1.1.1/SD/src/SD.cpp | 625 ++++++++ app/testdata/libraries/SD_1.1.1/SD/src/SD.h | 124 ++ .../SD_1.1.1/SD/src/utility/FatStructs.h | 418 ++++++ .../SD_1.1.1/SD/src/utility/Sd2Card.cpp | 719 ++++++++++ .../SD_1.1.1/SD/src/utility/Sd2Card.h | 260 ++++ .../SD_1.1.1/SD/src/utility/Sd2PinMap.h | 511 +++++++ .../libraries/SD_1.1.1/SD/src/utility/SdFat.h | 551 +++++++ .../SD_1.1.1/SD/src/utility/SdFatUtil.h | 75 + .../SD_1.1.1/SD/src/utility/SdFatmainpage.h | 202 +++ .../SD_1.1.1/SD/src/utility/SdFile.cpp | 1263 +++++++++++++++++ .../SD_1.1.1/SD/src/utility/SdInfo.h | 232 +++ .../SD_1.1.1/SD/src/utility/SdVolume.cpp | 295 ++++ .../libraries/SD_1.2.1/SD/README.adoc | 24 + .../SD/examples/CardInfo/CardInfo.ino | 116 ++ .../SD/examples/Datalogger/Datalogger.ino | 84 ++ .../SD/examples/DumpFile/DumpFile.ino | 65 + .../SD_1.2.1/SD/examples/Files/Files.ino | 75 + .../SD/examples/ReadWrite/ReadWrite.ino | 79 ++ .../SD/examples/listfiles/listfiles.ino | 80 ++ .../libraries/SD_1.2.1/SD/keywords.txt | 31 + .../libraries/SD_1.2.1/SD/library.properties | 9 + .../libraries/SD_1.2.1/SD/src/File.cpp | 146 ++ .../libraries/SD_1.2.1/SD/src/README.txt | 13 + app/testdata/libraries/SD_1.2.1/SD/src/SD.cpp | 628 ++++++++ app/testdata/libraries/SD_1.2.1/SD/src/SD.h | 127 ++ .../SD_1.2.1/SD/src/utility/FatStructs.h | 418 ++++++ .../SD_1.2.1/SD/src/utility/Sd2Card.cpp | 724 ++++++++++ .../SD_1.2.1/SD/src/utility/Sd2Card.h | 260 ++++ .../SD_1.2.1/SD/src/utility/Sd2PinMap.h | 511 +++++++ .../libraries/SD_1.2.1/SD/src/utility/SdFat.h | 551 +++++++ .../SD_1.2.1/SD/src/utility/SdFatUtil.h | 75 + .../SD_1.2.1/SD/src/utility/SdFatmainpage.h | 202 +++ .../SD_1.2.1/SD/src/utility/SdFile.cpp | 1263 +++++++++++++++++ .../SD_1.2.1/SD/src/utility/SdInfo.h | 232 +++ .../SD_1.2.1/SD/src/utility/SdVolume.cpp | 295 ++++ .../index_Bridge_only/library_index.json | 284 ++++ .../index_SD_only/library_index.json | 70 + 139 files changed, 20707 insertions(+), 6 deletions(-) create mode 100644 app/test/cc/arduino/contributions/UpdatableLibraryTest.java create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/README.adoc create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/examples/Bridge/Bridge.ino create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/examples/ConsoleAsciiTable/ConsoleAsciiTable.ino create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/examples/ConsolePixel/ConsolePixel.ino create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/examples/ConsoleRead/ConsoleRead.ino create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/examples/Datalogger/Datalogger.ino create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/examples/FileWriteScript/FileWriteScript.ino create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/examples/HttpClient/HttpClient.ino create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/examples/HttpClientConsole/HttpClientConsole.ino create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/examples/MailboxReadMessage/MailboxReadMessage.ino create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/examples/Process/Process.ino create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/examples/RemoteDueBlink/RemoteDueBlink.ino create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/examples/ShellCommands/ShellCommands.ino create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/examples/TemperatureWebPanel/TemperatureWebPanel.ino create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/examples/TemperatureWebPanel/www/index.html create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/examples/TemperatureWebPanel/www/zepto.min.js create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/examples/TimeCheck/TimeCheck.ino create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/examples/WiFiStatus/WiFiStatus.ino create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/examples/YunFirstConfig/YunFirstConfig.ino create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/examples/YunSerialTerminal/YunSerialTerminal.ino create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/keywords.txt create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/library.properties create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/src/Bridge.cpp create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/src/Bridge.h create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeClient.cpp create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeClient.h create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeSSLClient.cpp create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeSSLClient.h create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeServer.cpp create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeServer.h create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeUdp.cpp create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeUdp.h create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/src/Console.cpp create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/src/Console.h create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/src/FileIO.cpp create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/src/FileIO.h create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/src/HttpClient.cpp create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/src/HttpClient.h create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/src/Mailbox.cpp create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/src/Mailbox.h create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/src/Process.cpp create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/src/Process.h create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/src/YunClient.h create mode 100644 app/testdata/libraries/Bridge_1.6.3/Bridge/src/YunServer.h create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/README.adoc create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/examples/Bridge/Bridge.ino create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/examples/ConsoleAsciiTable/ConsoleAsciiTable.ino create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/examples/ConsolePixel/ConsolePixel.ino create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/examples/ConsoleRead/ConsoleRead.ino create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/examples/Datalogger/Datalogger.ino create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/examples/FileWriteScript/FileWriteScript.ino create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/examples/HttpClient/HttpClient.ino create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/examples/HttpClientConsole/HttpClientConsole.ino create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/examples/MailboxReadMessage/MailboxReadMessage.ino create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/examples/Process/Process.ino create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/examples/RemoteDueBlink/RemoteDueBlink.ino create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/examples/ShellCommands/ShellCommands.ino create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/examples/TemperatureWebPanel/TemperatureWebPanel.ino create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/examples/TemperatureWebPanel/www/index.html create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/examples/TemperatureWebPanel/www/zepto.min.js create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/examples/TimeCheck/TimeCheck.ino create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/examples/WiFiStatus/WiFiStatus.ino create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/examples/YunFirstConfig/YunFirstConfig.ino create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/examples/YunSerialTerminal/YunSerialTerminal.ino create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/keywords.txt create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/library.properties create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/src/Bridge.cpp create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/src/Bridge.h create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeClient.cpp create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeClient.h create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeSSLClient.cpp create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeSSLClient.h create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeServer.cpp create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeServer.h create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeUdp.cpp create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeUdp.h create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/src/Console.cpp create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/src/Console.h create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/src/FileIO.cpp create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/src/FileIO.h create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/src/HttpClient.cpp create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/src/HttpClient.h create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/src/Mailbox.cpp create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/src/Mailbox.h create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/src/Process.cpp create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/src/Process.h create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/src/YunClient.h create mode 100644 app/testdata/libraries/Bridge_1.7.0/Bridge/src/YunServer.h create mode 100644 app/testdata/libraries/SD_1.1.1/SD/README.adoc create mode 100644 app/testdata/libraries/SD_1.1.1/SD/examples/CardInfo/CardInfo.ino create mode 100644 app/testdata/libraries/SD_1.1.1/SD/examples/Datalogger/Datalogger.ino create mode 100644 app/testdata/libraries/SD_1.1.1/SD/examples/DumpFile/DumpFile.ino create mode 100644 app/testdata/libraries/SD_1.1.1/SD/examples/Files/Files.ino create mode 100644 app/testdata/libraries/SD_1.1.1/SD/examples/ReadWrite/ReadWrite.ino create mode 100644 app/testdata/libraries/SD_1.1.1/SD/examples/listfiles/listfiles.ino create mode 100644 app/testdata/libraries/SD_1.1.1/SD/keywords.txt create mode 100644 app/testdata/libraries/SD_1.1.1/SD/library.properties create mode 100644 app/testdata/libraries/SD_1.1.1/SD/src/File.cpp create mode 100644 app/testdata/libraries/SD_1.1.1/SD/src/README.txt create mode 100644 app/testdata/libraries/SD_1.1.1/SD/src/SD.cpp create mode 100644 app/testdata/libraries/SD_1.1.1/SD/src/SD.h create mode 100644 app/testdata/libraries/SD_1.1.1/SD/src/utility/FatStructs.h create mode 100644 app/testdata/libraries/SD_1.1.1/SD/src/utility/Sd2Card.cpp create mode 100644 app/testdata/libraries/SD_1.1.1/SD/src/utility/Sd2Card.h create mode 100644 app/testdata/libraries/SD_1.1.1/SD/src/utility/Sd2PinMap.h create mode 100644 app/testdata/libraries/SD_1.1.1/SD/src/utility/SdFat.h create mode 100644 app/testdata/libraries/SD_1.1.1/SD/src/utility/SdFatUtil.h create mode 100644 app/testdata/libraries/SD_1.1.1/SD/src/utility/SdFatmainpage.h create mode 100644 app/testdata/libraries/SD_1.1.1/SD/src/utility/SdFile.cpp create mode 100644 app/testdata/libraries/SD_1.1.1/SD/src/utility/SdInfo.h create mode 100644 app/testdata/libraries/SD_1.1.1/SD/src/utility/SdVolume.cpp create mode 100644 app/testdata/libraries/SD_1.2.1/SD/README.adoc create mode 100644 app/testdata/libraries/SD_1.2.1/SD/examples/CardInfo/CardInfo.ino create mode 100644 app/testdata/libraries/SD_1.2.1/SD/examples/Datalogger/Datalogger.ino create mode 100644 app/testdata/libraries/SD_1.2.1/SD/examples/DumpFile/DumpFile.ino create mode 100644 app/testdata/libraries/SD_1.2.1/SD/examples/Files/Files.ino create mode 100644 app/testdata/libraries/SD_1.2.1/SD/examples/ReadWrite/ReadWrite.ino create mode 100644 app/testdata/libraries/SD_1.2.1/SD/examples/listfiles/listfiles.ino create mode 100644 app/testdata/libraries/SD_1.2.1/SD/keywords.txt create mode 100644 app/testdata/libraries/SD_1.2.1/SD/library.properties create mode 100644 app/testdata/libraries/SD_1.2.1/SD/src/File.cpp create mode 100644 app/testdata/libraries/SD_1.2.1/SD/src/README.txt create mode 100644 app/testdata/libraries/SD_1.2.1/SD/src/SD.cpp create mode 100644 app/testdata/libraries/SD_1.2.1/SD/src/SD.h create mode 100644 app/testdata/libraries/SD_1.2.1/SD/src/utility/FatStructs.h create mode 100644 app/testdata/libraries/SD_1.2.1/SD/src/utility/Sd2Card.cpp create mode 100644 app/testdata/libraries/SD_1.2.1/SD/src/utility/Sd2Card.h create mode 100644 app/testdata/libraries/SD_1.2.1/SD/src/utility/Sd2PinMap.h create mode 100644 app/testdata/libraries/SD_1.2.1/SD/src/utility/SdFat.h create mode 100644 app/testdata/libraries/SD_1.2.1/SD/src/utility/SdFatUtil.h create mode 100644 app/testdata/libraries/SD_1.2.1/SD/src/utility/SdFatmainpage.h create mode 100644 app/testdata/libraries/SD_1.2.1/SD/src/utility/SdFile.cpp create mode 100644 app/testdata/libraries/SD_1.2.1/SD/src/utility/SdInfo.h create mode 100644 app/testdata/libraries/SD_1.2.1/SD/src/utility/SdVolume.cpp create mode 100644 app/testdata/libraries/index_Bridge_only/library_index.json create mode 100644 app/testdata/libraries/index_SD_only/library_index.json diff --git a/app/src/cc/arduino/contributions/ContributionsSelfCheck.java b/app/src/cc/arduino/contributions/ContributionsSelfCheck.java index ed593ae50..7812f62ad 100644 --- a/app/src/cc/arduino/contributions/ContributionsSelfCheck.java +++ b/app/src/cc/arduino/contributions/ContributionsSelfCheck.java @@ -73,12 +73,9 @@ public class ContributionsSelfCheck extends TimerTask { updateContributionIndex(); updateLibrariesIndex(); - boolean updatablePlatforms = BaseNoGui.indexer.getPackages().stream() - .flatMap(pack -> pack.getPlatforms().stream()) - .anyMatch(new UpdatablePlatformPredicate()); + boolean updatablePlatforms = checkForUpdatablePlatforms(); - boolean updatableLibraries = BaseNoGui.librariesIndexer.getIndex().getLibraries().stream() - .anyMatch(new UpdatableLibraryPredicate()); + boolean updatableLibraries = checkForUpdatableLibraries(); if (!updatableLibraries && !updatablePlatforms) { return; @@ -125,6 +122,17 @@ public class ContributionsSelfCheck extends TimerTask { }); } + static boolean checkForUpdatablePlatforms() { + return BaseNoGui.indexer.getPackages().stream() + .flatMap(pack -> pack.getPlatforms().stream()) + .anyMatch(new UpdatablePlatformPredicate()); + } + + static boolean checkForUpdatableLibraries() { + return BaseNoGui.librariesIndexer.getIndex().getLibraries().stream() + .anyMatch(new UpdatableLibraryPredicate()); + } + @Override public boolean cancel() { cancelled = true; diff --git a/app/src/cc/arduino/contributions/libraries/filters/UpdatableLibraryPredicate.java b/app/src/cc/arduino/contributions/libraries/filters/UpdatableLibraryPredicate.java index eaf328d54..2cb066ed7 100644 --- a/app/src/cc/arduino/contributions/libraries/filters/UpdatableLibraryPredicate.java +++ b/app/src/cc/arduino/contributions/libraries/filters/UpdatableLibraryPredicate.java @@ -31,6 +31,7 @@ package cc.arduino.contributions.libraries.filters; import cc.arduino.contributions.VersionComparator; import cc.arduino.contributions.libraries.ContributedLibrary; +import cc.arduino.contributions.libraries.LibrariesIndexer; import processing.app.BaseNoGui; import processing.app.packages.UserLibrary; @@ -40,6 +41,16 @@ import java.util.function.Predicate; public class UpdatableLibraryPredicate implements Predicate { + LibrariesIndexer librariesIndexer; + + public UpdatableLibraryPredicate() { + librariesIndexer = BaseNoGui.librariesIndexer; + } + + public UpdatableLibraryPredicate(LibrariesIndexer indexer) { + librariesIndexer = indexer; + } + @Override public boolean test(ContributedLibrary lib) { Optional installed = lib.getInstalledLibrary(); @@ -48,7 +59,7 @@ public class UpdatableLibraryPredicate implements Predicate } String installedVersion = installed.get().getVersion(); String libraryName = lib.getName(); - List libraries = BaseNoGui.librariesIndexer.getIndex().find(libraryName); + List libraries = librariesIndexer.getIndex().find(libraryName); return libraries.stream() .anyMatch(library -> VersionComparator.greaterThan(library.getParsedVersion(), installedVersion)); } diff --git a/app/test/cc/arduino/contributions/UpdatableLibraryTest.java b/app/test/cc/arduino/contributions/UpdatableLibraryTest.java new file mode 100644 index 000000000..1145e9896 --- /dev/null +++ b/app/test/cc/arduino/contributions/UpdatableLibraryTest.java @@ -0,0 +1,82 @@ +package cc.arduino.contributions; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +import cc.arduino.contributions.libraries.ContributedLibrary; +import cc.arduino.contributions.libraries.LibrariesIndexer; +import processing.app.BaseNoGui; +import processing.app.packages.UserLibraryFolder; +import processing.app.packages.UserLibraryFolder.Location; + +public class UpdatableLibraryTest { + + File testdata = new File( + UpdatableLibraryTest.class.getResource("/").getFile(), + "../testdata/libraries"); + File index_SD_only = new File(testdata, "index_SD_only"); + File SD111 = new File(testdata, "SD_1.1.1"); + File SD121 = new File(testdata, "SD_1.2.1"); + File index_Bridge_only = new File(testdata, "index_Bridge_only"); + File Bridge163 = new File(testdata, "Bridge_1.6.3"); + File Bridge170 = new File(testdata, "Bridge_1.7.0"); + + @Test + public void testUpdatableLibrary() throws Exception { + List folders = new ArrayList<>(); + folders.add(new UserLibraryFolder(SD111, Location.IDE_BUILTIN)); + + LibrariesIndexer indexer = new LibrariesIndexer(index_SD_only); + BaseNoGui.librariesIndexer = indexer; + indexer.parseIndex(); + indexer.setLibrariesFolders(folders); + + ContributedLibrary sdLib = indexer.getIndex().getInstalled("SD").get(); + assertTrue("SD lib is installed", sdLib.isLibraryInstalled()); + assertEquals("SD installed version", "1.1.1", sdLib.getParsedVersion()); + + assertTrue(ContributionsSelfCheck.checkForUpdatableLibraries()); + + folders.add(new UserLibraryFolder(SD121, Location.SKETCHBOOK)); + indexer.setLibrariesFolders(folders); + + sdLib = indexer.getIndex().getInstalled("SD").get(); + assertTrue("SD lib is installed", sdLib.isLibraryInstalled()); + assertEquals("SD installed version", "1.2.1", sdLib.getParsedVersion()); + + assertFalse(ContributionsSelfCheck.checkForUpdatableLibraries()); + } + + @Test + public void testUpdatableLibraryWithBundled() throws Exception { + List folders = new ArrayList<>(); + folders.add(new UserLibraryFolder(Bridge163, Location.IDE_BUILTIN)); + + LibrariesIndexer indexer = new LibrariesIndexer(index_Bridge_only); + BaseNoGui.librariesIndexer = indexer; + indexer.parseIndex(); + indexer.setLibrariesFolders(folders); + + ContributedLibrary l = indexer.getIndex().getInstalled("Bridge").get(); + assertTrue("Bridge lib is installed", l.isLibraryInstalled()); + assertEquals("Bridge installed version", "1.6.3", l.getParsedVersion()); + + assertTrue(ContributionsSelfCheck.checkForUpdatableLibraries()); + + folders.add(new UserLibraryFolder(Bridge170, Location.SKETCHBOOK)); + indexer.setLibrariesFolders(folders); + + l = indexer.getIndex().getInstalled("Bridge").get(); + assertTrue("Bridge lib is installed", l.isLibraryInstalled()); + assertEquals("Bridge installed version", "1.7.0", l.getParsedVersion()); + + assertFalse(ContributionsSelfCheck.checkForUpdatableLibraries()); + } +} diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/README.adoc b/app/testdata/libraries/Bridge_1.6.3/Bridge/README.adoc new file mode 100644 index 000000000..c660f86ee --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/README.adoc @@ -0,0 +1,24 @@ += Bridge Library for Arduino = + +The Bridge library simplifies communication between the ATmega32U4 and the AR9331. + +For more information about this library please visit us at +http://www.arduino.cc/en/Reference/YunBridgeLibrary + +== License == + +Copyright (c) 2014 Arduino LLC. 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 diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/Bridge/Bridge.ino b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/Bridge/Bridge.ino new file mode 100644 index 000000000..35c3aac5a --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/Bridge/Bridge.ino @@ -0,0 +1,183 @@ +/* + Arduino Yún Bridge example + + This example for the YunShield/Yún shows how + to use the Bridge library to access the digital and + analog pins on the board through REST calls. + It demonstrates how you can create your own API when + using REST style calls through the browser. + + Possible commands created in this shetch: + + "/arduino/digital/13" -> digitalRead(13) + "/arduino/digital/13/1" -> digitalWrite(13, HIGH) + "/arduino/analog/2/123" -> analogWrite(2, 123) + "/arduino/analog/2" -> analogRead(2) + "/arduino/mode/13/input" -> pinMode(13, INPUT) + "/arduino/mode/13/output" -> pinMode(13, OUTPUT) + + This example code is part of the public domain + + http://www.arduino.cc/en/Tutorial/Bridge + +*/ + +#include +#include +#include + +// Listen to the default port 5555, the Yún webserver +// will forward there all the HTTP requests you send +BridgeServer server; + +void setup() { + // Bridge startup + pinMode(13, OUTPUT); + digitalWrite(13, LOW); + Bridge.begin(); + digitalWrite(13, HIGH); + + // Listen for incoming connection only from localhost + // (no one from the external network could connect) + server.listenOnLocalhost(); + server.begin(); +} + +void loop() { + // Get clients coming from server + BridgeClient client = server.accept(); + + // There is a new client? + if (client) { + // Process request + process(client); + + // Close connection and free resources. + client.stop(); + } + + delay(50); // Poll every 50ms +} + +void process(BridgeClient client) { + // read the command + String command = client.readStringUntil('/'); + + // is "digital" command? + if (command == "digital") { + digitalCommand(client); + } + + // is "analog" command? + if (command == "analog") { + analogCommand(client); + } + + // is "mode" command? + if (command == "mode") { + modeCommand(client); + } +} + +void digitalCommand(BridgeClient client) { + int pin, value; + + // Read pin number + pin = client.parseInt(); + + // If the next character is a '/' it means we have an URL + // with a value like: "/digital/13/1" + if (client.read() == '/') { + value = client.parseInt(); + digitalWrite(pin, value); + } else { + value = digitalRead(pin); + } + + // Send feedback to client + client.print(F("Pin D")); + client.print(pin); + client.print(F(" set to ")); + client.println(value); + + // Update datastore key with the current pin value + String key = "D"; + key += pin; + Bridge.put(key, String(value)); +} + +void analogCommand(BridgeClient client) { + int pin, value; + + // Read pin number + pin = client.parseInt(); + + // If the next character is a '/' it means we have an URL + // with a value like: "/analog/5/120" + if (client.read() == '/') { + // Read value and execute command + value = client.parseInt(); + analogWrite(pin, value); + + // Send feedback to client + client.print(F("Pin D")); + client.print(pin); + client.print(F(" set to analog ")); + client.println(value); + + // Update datastore key with the current pin value + String key = "D"; + key += pin; + Bridge.put(key, String(value)); + } else { + // Read analog pin + value = analogRead(pin); + + // Send feedback to client + client.print(F("Pin A")); + client.print(pin); + client.print(F(" reads analog ")); + client.println(value); + + // Update datastore key with the current pin value + String key = "A"; + key += pin; + Bridge.put(key, String(value)); + } +} + +void modeCommand(BridgeClient client) { + int pin; + + // Read pin number + pin = client.parseInt(); + + // If the next character is not a '/' we have a malformed URL + if (client.read() != '/') { + client.println(F("error")); + return; + } + + String mode = client.readStringUntil('\r'); + + if (mode == "input") { + pinMode(pin, INPUT); + // Send feedback to client + client.print(F("Pin D")); + client.print(pin); + client.print(F(" configured as INPUT!")); + return; + } + + if (mode == "output") { + pinMode(pin, OUTPUT); + // Send feedback to client + client.print(F("Pin D")); + client.print(pin); + client.print(F(" configured as OUTPUT!")); + return; + } + + client.print(F("error: invalid mode ")); + client.print(mode); +} diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/ConsoleAsciiTable/ConsoleAsciiTable.ino b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/ConsoleAsciiTable/ConsoleAsciiTable.ino new file mode 100644 index 000000000..e8b07d7aa --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/ConsoleAsciiTable/ConsoleAsciiTable.ino @@ -0,0 +1,95 @@ +/* + Console ASCII table for YunShield/Yún + Prints out byte values in all possible formats: + * as raw binary values + * as ASCII-encoded decimal, hex, octal, and binary values + + For more on ASCII, see http://www.asciitable.com and http://en.wikipedia.org/wiki/ASCII + + The circuit: + - YunShield/Yún + + created 2006 + by Nicholas Zambetti + http://www.zambetti.com + modified 9 Apr 2012 + by Tom Igoe + modified 22 May 2013 + by Cristian Maglie + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/ConsoleAsciiTable + + */ + +#include + +void setup() { + //Initialize Console and wait for port to open: + Bridge.begin(); + Console.begin(); + + // Uncomment the following line to enable buffering: + // - better transmission speed and efficiency + // - needs to call Console.flush() to ensure that all + // transmitted data is sent + + //Console.buffer(64); + + while (!Console) { + ; // wait for Console port to connect. + } + + // prints title with ending line break + Console.println("ASCII Table ~ Character Map"); +} + +// first visible ASCIIcharacter '!' is number 33: +int thisByte = 33; +// you can also write ASCII characters in single quotes. +// for example. '!' is the same as 33, so you could also use this: +//int thisByte = '!'; + +void loop() { + // prints value unaltered, i.e. the raw binary version of the + // byte. The Console monitor interprets all bytes as + // ASCII, so 33, the first number, will show up as '!' + Console.write(thisByte); + + Console.print(", dec: "); + // prints value as string as an ASCII-encoded decimal (base 10). + // Decimal is the default format for Console.print() and Console.println(), + // so no modifier is needed: + Console.print(thisByte); + // But you can declare the modifier for decimal if you want to. + //this also works if you uncomment it: + + // Console.print(thisByte, DEC); + + Console.print(", hex: "); + // prints value as string in hexadecimal (base 16): + Console.print(thisByte, HEX); + + Console.print(", oct: "); + // prints value as string in octal (base 8); + Console.print(thisByte, OCT); + + Console.print(", bin: "); + // prints value as string in binary (base 2) + // also prints ending line break: + Console.println(thisByte, BIN); + + // if printed last visible character '~' or 126, stop: + if (thisByte == 126) { // you could also use if (thisByte == '~') { + // ensure the latest bit of data is sent + Console.flush(); + + // This loop loops forever and does nothing + while (true) { + continue; + } + } + // go on to the next character + thisByte++; +} diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/ConsolePixel/ConsolePixel.ino b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/ConsolePixel/ConsolePixel.ino new file mode 100644 index 000000000..6479b135b --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/ConsolePixel/ConsolePixel.ino @@ -0,0 +1,63 @@ +/* + Console Pixel + + An example of using YunShield/Yún board to receive data from the + Console on the Yún. In this case, the board turns on an LED when + it receives the character 'H', and turns off the LED when it + receives the character 'L'. + + To see the Console, pick your Yún's name and IP address in the Port menu + then open the Port Monitor. You can also see it by opening a terminal window + and typing + ssh root@ yourYunsName.local 'telnet localhost 6571' + then pressing enter. When prompted for the password, enter it. + + + The circuit: + * LED connected from digital pin 13 to ground + + created 2006 + by David A. Mellis + modified 25 Jun 2013 + by Tom Igoe + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/ConsolePixel + + */ + +#include + +const int ledPin = 13; // the pin that the LED is attached to +char incomingByte; // a variable to read incoming Console data into + +void setup() { + Bridge.begin(); // Initialize Bridge + Console.begin(); // Initialize Console + + // Wait for the Console port to connect + while (!Console); + + Console.println("type H or L to turn pin 13 on or off"); + + // initialize the LED pin as an output: + pinMode(ledPin, OUTPUT); +} + +void loop() { + // see if there's incoming Console data: + if (Console.available() > 0) { + // read the oldest byte in the Console buffer: + incomingByte = Console.read(); + Console.println(incomingByte); + // if it's a capital H (ASCII 72), turn on the LED: + if (incomingByte == 'H') { + digitalWrite(ledPin, HIGH); + } + // if it's an L (ASCII 76) turn off the LED: + if (incomingByte == 'L') { + digitalWrite(ledPin, LOW); + } + } +} diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/ConsoleRead/ConsoleRead.ino b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/ConsoleRead/ConsoleRead.ino new file mode 100644 index 000000000..fc63fcc6d --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/ConsoleRead/ConsoleRead.ino @@ -0,0 +1,58 @@ +/* +Console Read example for YunShield/Yún + + Read data coming from bridge using the Console.read() function + and store it in a string. + + To see the Console, pick your Yún's name and IP address in the Port menu + then open the Port Monitor. You can also see it by opening a terminal window + and typing: + ssh root@ yourYunsName.local 'telnet localhost 6571' + then pressing enter. When prompted for the password, enter it. + + created 13 Jun 2013 + by Angelo Scialabba + modified 16 June 2013 + by Tom Igoe + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/ConsoleRead + + */ + +#include + +String name; + +void setup() { + // Initialize Console and wait for port to open: + Bridge.begin(); + Console.begin(); + + // Wait for Console port to connect + while (!Console); + + Console.println("Hi, what's your name?"); +} + +void loop() { + if (Console.available() > 0) { + char c = Console.read(); // read the next char received + // look for the newline character, this is the last character in the string + if (c == '\n') { + //print text with the name received + Console.print("Hi "); + Console.print(name); + Console.println("! Nice to meet you!"); + Console.println(); + // Ask again for name and clear the old name + Console.println("Hi, what's your name?"); + name = ""; // clear the name string + } else { // if the buffer is empty Cosole.read() returns -1 + name += c; // append the read char from Console to the name string + } + } else { + delay(100); + } +} diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/Datalogger/Datalogger.ino b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/Datalogger/Datalogger.ino new file mode 100644 index 000000000..cc84828a0 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/Datalogger/Datalogger.ino @@ -0,0 +1,102 @@ +/* + SD card datalogger + + This example shows how to log data from three analog sensors + to an SD card mounted on the YunShield/Yún using the Bridge library. + + The circuit: + * analog sensors on analog pins 0, 1 and 2 + * SD card attached to SD card slot of the YunShield/Yún + + Prepare your SD card creating an empty folder in the SD root + named "arduino". This will ensure that the Yún will create a link + to the SD to the "/mnt/sd" path. + + You can remove the SD card while the Linux and the + sketch are running but be careful not to remove it while + the system is writing to it. + + created 24 Nov 2010 + modified 9 Apr 2012 + by Tom Igoe + adapted to the Yún Bridge library 20 Jun 2013 + by Federico Vanzati + modified 21 Jun 2013 + by Tom Igoe + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/YunDatalogger + + */ + +#include + +void setup() { + // Initialize the Bridge and the Serial + Bridge.begin(); + Serial.begin(9600); + FileSystem.begin(); + + while (!SerialUSB); // wait for Serial port to connect. + SerialUSB.println("Filesystem datalogger\n"); +} + + +void loop() { + // make a string that start with a timestamp for assembling the data to log: + String dataString; + dataString += getTimeStamp(); + dataString += " = "; + + // read three sensors and append to the string: + for (int analogPin = 0; analogPin < 3; analogPin++) { + int sensor = analogRead(analogPin); + dataString += String(sensor); + if (analogPin < 2) { + dataString += ","; // separate the values with a comma + } + } + + // open the file. note that only one file can be open at a time, + // so you have to close this one before opening another. + // The FileSystem card is mounted at the following "/mnt/FileSystema1" + File dataFile = FileSystem.open("/mnt/sd/datalog.txt", FILE_APPEND); + + // if the file is available, write to it: + if (dataFile) { + dataFile.println(dataString); + dataFile.close(); + // print to the serial port too: + SerialUSB.println(dataString); + } + // if the file isn't open, pop up an error: + else { + SerialUSB.println("error opening datalog.txt"); + } + + delay(15000); + +} + +// This function return a string with the time stamp +String getTimeStamp() { + String result; + Process time; + // date is a command line utility to get the date and the time + // in different formats depending on the additional parameter + time.begin("date"); + time.addParameter("+%D-%T"); // parameters: D for the complete date mm/dd/yy + // T for the time hh:mm:ss + time.run(); // run the command + + // read the output of the command + while (time.available() > 0) { + char c = time.read(); + if (c != '\n') { + result += c; + } + } + + return result; +} diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/FileWriteScript/FileWriteScript.ino b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/FileWriteScript/FileWriteScript.ino new file mode 100644 index 000000000..e080bce36 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/FileWriteScript/FileWriteScript.ino @@ -0,0 +1,83 @@ +/* + Write to file using FileIO classes. + + This sketch demonstrate how to write file into the YunShield/Yún filesystem. + A shell script file is created in /tmp, and it is executed afterwards. + + created 7 June 2010 + by Cristian Maglie + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/FileWriteScript + + */ + +#include + +void setup() { + // Setup Bridge (needed every time we communicate with the Arduino Yún) + Bridge.begin(); + // Initialize the Serial + SerialUSB.begin(9600); + + while (!SerialUSB); // wait for Serial port to connect. + SerialUSB.println("File Write Script example\n\n"); + + // Setup File IO + FileSystem.begin(); + + // Upload script used to gain network statistics + uploadScript(); +} + +void loop() { + // Run stats script every 5 secs. + runScript(); + delay(5000); +} + +// this function creates a file into the linux processor that contains a shell script +// to check the network traffic of the WiFi interface +void uploadScript() { + // Write our shell script in /tmp + // Using /tmp stores the script in RAM this way we can preserve + // the limited amount of FLASH erase/write cycles + File script = FileSystem.open("/tmp/wlan-stats.sh", FILE_WRITE); + // Shell script header + script.print("#!/bin/sh\n"); + // shell commands: + // ifconfig: is a command line utility for controlling the network interfaces. + // wlan0 is the interface we want to query + // grep: search inside the output of the ifconfig command the "RX bytes" keyword + // and extract the line that contains it + script.print("ifconfig wlan0 | grep 'RX bytes'\n"); + script.close(); // close the file + + // Make the script executable + Process chmod; + chmod.begin("chmod"); // chmod: change mode + chmod.addParameter("+x"); // x stays for executable + chmod.addParameter("/tmp/wlan-stats.sh"); // path to the file to make it executable + chmod.run(); +} + + +// this function run the script and read the output data +void runScript() { + // Run the script and show results on the Serial + Process myscript; + myscript.begin("/tmp/wlan-stats.sh"); + myscript.run(); + + String output = ""; + + // read the output of the script + while (myscript.available()) { + output += (char)myscript.read(); + } + // remove the blank spaces at the beginning and the ending of the string + output.trim(); + SerialUSB.println(output); + SerialUSB.flush(); +} diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/HttpClient/HttpClient.ino b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/HttpClient/HttpClient.ino new file mode 100644 index 000000000..47a37c3f2 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/HttpClient/HttpClient.ino @@ -0,0 +1,51 @@ +/* + Yún HTTP Client + + This example for the YunShield/Yún shows how create a basic + HTTP client that connects to the internet and downloads + content. In this case, you'll connect to the Arduino + website and download a version of the logo as ASCII text. + + created by Tom igoe + May 2013 + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/HttpClient + + */ + +#include +#include + +void setup() { + // Bridge takes about two seconds to start up + // it can be helpful to use the on-board LED + // as an indicator for when it has initialized + pinMode(13, OUTPUT); + digitalWrite(13, LOW); + Bridge.begin(); + digitalWrite(13, HIGH); + + SerialUSB.begin(9600); + + while (!SerialUSB); // wait for a serial connection +} + +void loop() { + // Initialize the client library + HttpClient client; + + // Make a HTTP request: + client.get("http://www.arduino.cc/asciilogo.txt"); + + // if there are incoming bytes available + // from the server, read them and print them: + while (client.available()) { + char c = client.read(); + SerialUSB.print(c); + } + SerialUSB.flush(); + + delay(5000); +} diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/HttpClientConsole/HttpClientConsole.ino b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/HttpClientConsole/HttpClientConsole.ino new file mode 100644 index 000000000..3b07f601c --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/HttpClientConsole/HttpClientConsole.ino @@ -0,0 +1,53 @@ +/* + Yún HTTP Client Console version for Arduino Uno and Mega using Yún Shield + + This example for the YunShield/Yún shows how create a basic + HTTP client that connects to the internet and downloads + content. In this case, you'll connect to the Arduino + website and download a version of the logo as ASCII text. + + created by Tom igoe + May 2013 + modified by Marco Brianza to use Console + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/HttpClient + + */ + +#include +#include +#include + +void setup() { + // Bridge takes about two seconds to start up + // it can be helpful to use the on-board LED + // as an indicator for when it has initialized + pinMode(13, OUTPUT); + digitalWrite(13, LOW); + Bridge.begin(); + digitalWrite(13, HIGH); + + Console.begin(); + + while (!Console); // wait for a serial connection +} + +void loop() { + // Initialize the client library + HttpClient client; + + // Make a HTTP request: + client.get("http://www.arduino.cc/asciilogo.txt"); + + // if there are incoming bytes available + // from the server, read them and print them: + while (client.available()) { + char c = client.read(); + Console.print(c); + } + Console.flush(); + + delay(5000); +} diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/MailboxReadMessage/MailboxReadMessage.ino b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/MailboxReadMessage/MailboxReadMessage.ino new file mode 100644 index 000000000..11aaecd3d --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/MailboxReadMessage/MailboxReadMessage.ino @@ -0,0 +1,58 @@ +/* + Read Messages from the Mailbox + + This example for the YunShield/Yún shows how to + read the messages queue, called Mailbox, using the + Bridge library. + The messages can be sent to the queue through REST calls. + Appen the message in the URL after the keyword "/mailbox". + Example + + "/mailbox/hello" + + created 3 Feb 2014 + by Federico Vanzati & Federico Fissore + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/MailboxReadMessage + + */ + +#include + +void setup() { + pinMode(13, OUTPUT); + digitalWrite(13, LOW); + // Initialize Bridge and Mailbox + Bridge.begin(); + Mailbox.begin(); + digitalWrite(13, HIGH); + + // Initialize Serial + SerialUSB.begin(9600); + + // Wait until a Serial Monitor is connected. + while (!SerialUSB); + + SerialUSB.println("Mailbox Read Message\n"); + SerialUSB.println("The Mailbox is checked every 10 seconds. The incoming messages will be shown below.\n"); +} + +void loop() { + String message; + + // if there is a message in the Mailbox + if (Mailbox.messageAvailable()) { + // read all the messages present in the queue + while (Mailbox.messageAvailable()) { + Mailbox.readMessage(message); + SerialUSB.println(message); + } + + SerialUSB.println("Waiting 10 seconds before checking the Mailbox again"); + } + + // wait 10 seconds + delay(10000); +} diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/Process/Process.ino b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/Process/Process.ino new file mode 100644 index 000000000..7f5752c77 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/Process/Process.ino @@ -0,0 +1,71 @@ +/* + Running process using Process class. + + This sketch demonstrate how to run linux processes + using a YunShield/Yún + + created 5 Jun 2013 + by Cristian Maglie + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/Process + + */ + +#include + +void setup() { + // Initialize Bridge + Bridge.begin(); + + // Initialize Serial + SerialUSB.begin(9600); + + // Wait until a Serial Monitor is connected. + while (!SerialUSB); + + // run various example processes + runCurl(); + runCpuInfo(); +} + +void loop() { + // Do nothing here. +} + +void runCurl() { + // Launch "curl" command and get Arduino ascii art logo from the network + // curl is command line program for transferring data using different internet protocols + Process p; // Create a process and call it "p" + p.begin("curl"); // Process that launch the "curl" command + p.addParameter("http://www.arduino.cc/asciilogo.txt"); // Add the URL parameter to "curl" + p.run(); // Run the process and wait for its termination + + // Print arduino logo over the Serial + // A process output can be read with the stream methods + while (p.available() > 0) { + char c = p.read(); + SerialUSB.print(c); + } + // Ensure the last bit of data is sent. + SerialUSB.flush(); +} + +void runCpuInfo() { + // Launch "cat /proc/cpuinfo" command (shows info on Atheros CPU) + // cat is a command line utility that shows the content of a file + Process p; // Create a process and call it "p" + p.begin("cat"); // Process that launch the "cat" command + p.addParameter("/proc/cpuinfo"); // Add the cpuifo file path as parameter to cut + p.run(); // Run the process and wait for its termination + + // Print command output on the SerialUSB. + // A process output can be read with the stream methods + while (p.available() > 0) { + char c = p.read(); + SerialUSB.print(c); + } + // Ensure the last bit of data is sent. + SerialUSB.flush(); +} diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/RemoteDueBlink/RemoteDueBlink.ino b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/RemoteDueBlink/RemoteDueBlink.ino new file mode 100644 index 000000000..4b5d2713c --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/RemoteDueBlink/RemoteDueBlink.ino @@ -0,0 +1,33 @@ +/* + 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://www.arduino.cc + + This example code is in the public domain. + + modified 8 May 2014 + by Scott Fitzgerald + + modified by Marco Brianza to show the remote sketch update feature on Arduino Due using Yún Shield + */ + +#include + +// the setup function runs once when you press reset or power the board +void setup() { + checkForRemoteSketchUpdate(); + // initialize digital pin 13 as an output. + pinMode(13, OUTPUT); +} + +// the loop function runs over and over again forever +void loop() { + digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level) + delay(100); // wait for a second + digitalWrite(13, LOW); // turn the LED off by making the voltage LOW + delay(100); // wait for a second +} diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/ShellCommands/ShellCommands.ino b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/ShellCommands/ShellCommands.ino new file mode 100644 index 000000000..acd82896e --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/ShellCommands/ShellCommands.ino @@ -0,0 +1,52 @@ +/* + Running shell commands using Process class. + + This sketch demonstrate how to run linux shell commands + using a YunShield/Yún. It runs the wifiCheck script on the Linux side + of the Yún, then uses grep to get just the signal strength line. + Then it uses parseInt() to read the wifi signal strength as an integer, + and finally uses that number to fade an LED using analogWrite(). + + The circuit: + * YunShield/Yún with LED connected to pin 9 + + created 12 Jun 2013 + by Cristian Maglie + modified 25 June 2013 + by Tom Igoe + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/ShellCommands + + */ + +#include + +void setup() { + Bridge.begin(); // Initialize the Bridge + SerialUSB.begin(9600); // Initialize the Serial + + // Wait until a Serial Monitor is connected. + while (!SerialUSB); +} + +void loop() { + Process p; + // This command line runs the WifiStatus script, (/usr/bin/pretty-wifi-info.lua), then + // sends the result to the grep command to look for a line containing the word + // "Signal:" the result is passed to this sketch: + p.runShellCommand("/usr/bin/pretty-wifi-info.lua | grep Signal"); + + // do nothing until the process finishes, so you get the whole output: + while (p.running()); + + // Read command output. runShellCommand() should have passed "Signal: xx&": + while (p.available()) { + int result = p.parseInt(); // look for an integer + int signal = map(result, 0, 100, 0, 255); // map result from 0-100 range to 0-255 + analogWrite(9, signal); // set the brightness of LED on pin 9 + SerialUSB.println(result); // print the number as well + } + delay(5000); // wait 5 seconds before you do it again +} diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/TemperatureWebPanel/TemperatureWebPanel.ino b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/TemperatureWebPanel/TemperatureWebPanel.ino new file mode 100644 index 000000000..7bf25a8a0 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/TemperatureWebPanel/TemperatureWebPanel.ino @@ -0,0 +1,122 @@ +/* + Temperature web interface + + This example shows how to serve data from an analog input + via the YunShield/Yún built-in webserver using the Bridge library. + + The circuit: + * TMP36 temperature sensor on analog pin A1 + * SD card attached to SD card slot of the YunShield/Yún + + This sketch must be uploaded via wifi. REST API must be set to "open". + + Prepare your SD card with an empty folder in the SD root + named "arduino" and a subfolder of that named "www". + This will ensure that the Yún will create a link + to the SD to the "/mnt/sd" path. + + In this sketch folder is a basic webpage and a copy of zepto.js, a + minimized version of jQuery. When you upload your sketch, these files + will be placed in the /arduino/www/TemperatureWebPanel folder on your SD card. + + You can then go to http://arduino.local/sd/TemperatureWebPanel + to see the output of this sketch. + + You can remove the SD card while the Linux and the + sketch are running but be careful not to remove it while + the system is writing to it. + + created 6 July 2013 + by Tom Igoe + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/TemperatureWebPanel + + */ + +#include +#include +#include + +// Listen on default port 5555, the webserver on the Yún +// will forward there all the HTTP requests for us. +BridgeServer server; +String startString; +long hits = 0; + +void setup() { + SerialUSB.begin(9600); + + // Bridge startup + pinMode(13, OUTPUT); + digitalWrite(13, LOW); + Bridge.begin(); + digitalWrite(13, HIGH); + + // using A0 and A2 as vcc and gnd for the TMP36 sensor: + pinMode(A0, OUTPUT); + pinMode(A2, OUTPUT); + digitalWrite(A0, HIGH); + digitalWrite(A2, LOW); + + // Listen for incoming connection only from localhost + // (no one from the external network could connect) + server.listenOnLocalhost(); + server.begin(); + + // get the time that this sketch started: + Process startTime; + startTime.runShellCommand("date"); + while (startTime.available()) { + char c = startTime.read(); + startString += c; + } +} + +void loop() { + // Get clients coming from server + BridgeClient client = server.accept(); + + // There is a new client? + if (client) { + // read the command + String command = client.readString(); + command.trim(); //kill whitespace + SerialUSB.println(command); + // is "temperature" command? + if (command == "temperature") { + + // get the time from the server: + Process time; + time.runShellCommand("date"); + String timeString = ""; + while (time.available()) { + char c = time.read(); + timeString += c; + } + SerialUSB.println(timeString); + int sensorValue = analogRead(A1); + // convert the reading to millivolts: + float voltage = sensorValue * (5000.0f / 1024.0f); + // convert the millivolts to temperature celsius: + float temperature = (voltage - 500.0f) / 10.0f; + // print the temperature: + client.print("Current time on the Yún: "); + client.println(timeString); + client.print("
Current temperature: "); + client.print(temperature); + client.print(" °C"); + client.print("
This sketch has been running since "); + client.print(startString); + client.print("
Hits so far: "); + client.print(hits); + } + + // Close connection and free resources. + client.stop(); + hits++; + } + + delay(50); // Poll every 50ms +} diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/TemperatureWebPanel/www/index.html b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/TemperatureWebPanel/www/index.html new file mode 100644 index 000000000..c6b674771 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/TemperatureWebPanel/www/index.html @@ -0,0 +1,16 @@ + + + + + + + + + 0 + + + diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/TemperatureWebPanel/www/zepto.min.js b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/TemperatureWebPanel/www/zepto.min.js new file mode 100644 index 000000000..dbe4e3c3f --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/TemperatureWebPanel/www/zepto.min.js @@ -0,0 +1,2 @@ +/* Zepto v1.0-1-ga3cab6c - polyfill zepto detect event ajax form fx - zeptojs.com/license */ +(function(a){String.prototype.trim===a&&(String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g,"")}),Array.prototype.reduce===a&&(Array.prototype.reduce=function(b){if(this===void 0||this===null)throw new TypeError;var c=Object(this),d=c.length>>>0,e=0,f;if(typeof b!="function")throw new TypeError;if(d==0&&arguments.length==1)throw new TypeError;if(arguments.length>=2)f=arguments[1];else do{if(e in c){f=c[e++];break}if(++e>=d)throw new TypeError}while(!0);while(e0?c.fn.concat.apply([],a):a}function O(a){return a.replace(/::/g,"/").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/_/g,"-").toLowerCase()}function P(a){return a in j?j[a]:j[a]=new RegExp("(^|\\s)"+a+"(\\s|$)")}function Q(a,b){return typeof b=="number"&&!l[O(a)]?b+"px":b}function R(a){var b,c;return i[a]||(b=h.createElement(a),h.body.appendChild(b),c=k(b,"").getPropertyValue("display"),b.parentNode.removeChild(b),c=="none"&&(c="block"),i[a]=c),i[a]}function S(a){return"children"in a?f.call(a.children):c.map(a.childNodes,function(a){if(a.nodeType==1)return a})}function T(c,d,e){for(b in d)e&&(J(d[b])||K(d[b]))?(J(d[b])&&!J(c[b])&&(c[b]={}),K(d[b])&&!K(c[b])&&(c[b]=[]),T(c[b],d[b],e)):d[b]!==a&&(c[b]=d[b])}function U(b,d){return d===a?c(b):c(b).filter(d)}function V(a,b,c,d){return F(b)?b.call(a,c,d):b}function W(a,b,c){c==null?a.removeAttribute(b):a.setAttribute(b,c)}function X(b,c){var d=b.className,e=d&&d.baseVal!==a;if(c===a)return e?d.baseVal:d;e?d.baseVal=c:b.className=c}function Y(a){var b;try{return a?a=="true"||(a=="false"?!1:a=="null"?null:isNaN(b=Number(a))?/^[\[\{]/.test(a)?c.parseJSON(a):a:b):a}catch(d){return a}}function Z(a,b){b(a);for(var c in a.childNodes)Z(a.childNodes[c],b)}var a,b,c,d,e=[],f=e.slice,g=e.filter,h=window.document,i={},j={},k=h.defaultView.getComputedStyle,l={"column-count":1,columns:1,"font-weight":1,"line-height":1,opacity:1,"z-index":1,zoom:1},m=/^\s*<(\w+|!)[^>]*>/,n=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,o=/^(?:body|html)$/i,p=["val","css","html","text","data","width","height","offset"],q=["after","prepend","before","append"],r=h.createElement("table"),s=h.createElement("tr"),t={tr:h.createElement("tbody"),tbody:r,thead:r,tfoot:r,td:s,th:s,"*":h.createElement("div")},u=/complete|loaded|interactive/,v=/^\.([\w-]+)$/,w=/^#([\w-]*)$/,x=/^[\w-]+$/,y={},z=y.toString,A={},B,C,D=h.createElement("div");return A.matches=function(a,b){if(!a||a.nodeType!==1)return!1;var c=a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.matchesSelector;if(c)return c.call(a,b);var d,e=a.parentNode,f=!e;return f&&(e=D).appendChild(a),d=~A.qsa(e,b).indexOf(a),f&&D.removeChild(a),d},B=function(a){return a.replace(/-+(.)?/g,function(a,b){return b?b.toUpperCase():""})},C=function(a){return g.call(a,function(b,c){return a.indexOf(b)==c})},A.fragment=function(b,d,e){b.replace&&(b=b.replace(n,"<$1>")),d===a&&(d=m.test(b)&&RegExp.$1),d in t||(d="*");var g,h,i=t[d];return i.innerHTML=""+b,h=c.each(f.call(i.childNodes),function(){i.removeChild(this)}),J(e)&&(g=c(h),c.each(e,function(a,b){p.indexOf(a)>-1?g[a](b):g.attr(a,b)})),h},A.Z=function(a,b){return a=a||[],a.__proto__=c.fn,a.selector=b||"",a},A.isZ=function(a){return a instanceof A.Z},A.init=function(b,d){if(!b)return A.Z();if(F(b))return c(h).ready(b);if(A.isZ(b))return b;var e;if(K(b))e=M(b);else if(I(b))e=[J(b)?c.extend({},b):b],b=null;else if(m.test(b))e=A.fragment(b.trim(),RegExp.$1,d),b=null;else{if(d!==a)return c(d).find(b);e=A.qsa(h,b)}return A.Z(e,b)},c=function(a,b){return A.init(a,b)},c.extend=function(a){var b,c=f.call(arguments,1);return typeof a=="boolean"&&(b=a,a=c.shift()),c.forEach(function(c){T(a,c,b)}),a},A.qsa=function(a,b){var c;return H(a)&&w.test(b)?(c=a.getElementById(RegExp.$1))?[c]:[]:a.nodeType!==1&&a.nodeType!==9?[]:f.call(v.test(b)?a.getElementsByClassName(RegExp.$1):x.test(b)?a.getElementsByTagName(b):a.querySelectorAll(b))},c.contains=function(a,b){return a!==b&&a.contains(b)},c.type=E,c.isFunction=F,c.isWindow=G,c.isArray=K,c.isPlainObject=J,c.isEmptyObject=function(a){var b;for(b in a)return!1;return!0},c.inArray=function(a,b,c){return e.indexOf.call(b,a,c)},c.camelCase=B,c.trim=function(a){return a.trim()},c.uuid=0,c.support={},c.expr={},c.map=function(a,b){var c,d=[],e,f;if(L(a))for(e=0;e=0?b:b+this.length]},toArray:function(){return this.get()},size:function(){return this.length},remove:function(){return this.each(function(){this.parentNode!=null&&this.parentNode.removeChild(this)})},each:function(a){return e.every.call(this,function(b,c){return a.call(b,c,b)!==!1}),this},filter:function(a){return F(a)?this.not(this.not(a)):c(g.call(this,function(b){return A.matches(b,a)}))},add:function(a,b){return c(C(this.concat(c(a,b))))},is:function(a){return this.length>0&&A.matches(this[0],a)},not:function(b){var d=[];if(F(b)&&b.call!==a)this.each(function(a){b.call(this,a)||d.push(this)});else{var e=typeof b=="string"?this.filter(b):L(b)&&F(b.item)?f.call(b):c(b);this.forEach(function(a){e.indexOf(a)<0&&d.push(a)})}return c(d)},has:function(a){return this.filter(function(){return I(a)?c.contains(this,a):c(this).find(a).size()})},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){var a=this[0];return a&&!I(a)?a:c(a)},last:function(){var a=this[this.length-1];return a&&!I(a)?a:c(a)},find:function(a){var b,d=this;return typeof a=="object"?b=c(a).filter(function(){var a=this;return e.some.call(d,function(b){return c.contains(b,a)})}):this.length==1?b=c(A.qsa(this[0],a)):b=this.map(function(){return A.qsa(this,a)}),b},closest:function(a,b){var d=this[0],e=!1;typeof a=="object"&&(e=c(a));while(d&&!(e?e.indexOf(d)>=0:A.matches(d,a)))d=d!==b&&!H(d)&&d.parentNode;return c(d)},parents:function(a){var b=[],d=this;while(d.length>0)d=c.map(d,function(a){if((a=a.parentNode)&&!H(a)&&b.indexOf(a)<0)return b.push(a),a});return U(b,a)},parent:function(a){return U(C(this.pluck("parentNode")),a)},children:function(a){return U(this.map(function(){return S(this)}),a)},contents:function(){return this.map(function(){return f.call(this.childNodes)})},siblings:function(a){return U(this.map(function(a,b){return g.call(S(b.parentNode),function(a){return a!==b})}),a)},empty:function(){return this.each(function(){this.innerHTML=""})},pluck:function(a){return c.map(this,function(b){return b[a]})},show:function(){return this.each(function(){this.style.display=="none"&&(this.style.display=null),k(this,"").getPropertyValue("display")=="none"&&(this.style.display=R(this.nodeName))})},replaceWith:function(a){return this.before(a).remove()},wrap:function(a){var b=F(a);if(this[0]&&!b)var d=c(a).get(0),e=d.parentNode||this.length>1;return this.each(function(f){c(this).wrapAll(b?a.call(this,f):e?d.cloneNode(!0):d)})},wrapAll:function(a){if(this[0]){c(this[0]).before(a=c(a));var b;while((b=a.children()).length)a=b.first();c(a).append(this)}return this},wrapInner:function(a){var b=F(a);return this.each(function(d){var e=c(this),f=e.contents(),g=b?a.call(this,d):a;f.length?f.wrapAll(g):e.append(g)})},unwrap:function(){return this.parent().each(function(){c(this).replaceWith(c(this).children())}),this},clone:function(){return this.map(function(){return this.cloneNode(!0)})},hide:function(){return this.css("display","none")},toggle:function(b){return this.each(function(){var d=c(this);(b===a?d.css("display")=="none":b)?d.show():d.hide()})},prev:function(a){return c(this.pluck("previousElementSibling")).filter(a||"*")},next:function(a){return c(this.pluck("nextElementSibling")).filter(a||"*")},html:function(b){return b===a?this.length>0?this[0].innerHTML:null:this.each(function(a){var d=this.innerHTML;c(this).empty().append(V(this,b,a,d))})},text:function(b){return b===a?this.length>0?this[0].textContent:null:this.each(function(){this.textContent=b})},attr:function(c,d){var e;return typeof c=="string"&&d===a?this.length==0||this[0].nodeType!==1?a:c=="value"&&this[0].nodeName=="INPUT"?this.val():!(e=this[0].getAttribute(c))&&c in this[0]?this[0][c]:e:this.each(function(a){if(this.nodeType!==1)return;if(I(c))for(b in c)W(this,b,c[b]);else W(this,c,V(this,d,a,this.getAttribute(c)))})},removeAttr:function(a){return this.each(function(){this.nodeType===1&&W(this,a)})},prop:function(b,c){return c===a?this[0]&&this[0][b]:this.each(function(a){this[b]=V(this,c,a,this[b])})},data:function(b,c){var d=this.attr("data-"+O(b),c);return d!==null?Y(d):a},val:function(b){return b===a?this[0]&&(this[0].multiple?c(this[0]).find("option").filter(function(a){return this.selected}).pluck("value"):this[0].value):this.each(function(a){this.value=V(this,b,a,this.value)})},offset:function(a){if(a)return this.each(function(b){var d=c(this),e=V(this,a,b,d.offset()),f=d.offsetParent().offset(),g={top:e.top-f.top,left:e.left-f.left};d.css("position")=="static"&&(g.position="relative"),d.css(g)});if(this.length==0)return null;var b=this[0].getBoundingClientRect();return{left:b.left+window.pageXOffset,top:b.top+window.pageYOffset,width:Math.round(b.width),height:Math.round(b.height)}},css:function(a,c){if(arguments.length<2&&typeof a=="string")return this[0]&&(this[0].style[B(a)]||k(this[0],"").getPropertyValue(a));var d="";if(E(a)=="string")!c&&c!==0?this.each(function(){this.style.removeProperty(O(a))}):d=O(a)+":"+Q(a,c);else for(b in a)!a[b]&&a[b]!==0?this.each(function(){this.style.removeProperty(O(b))}):d+=O(b)+":"+Q(b,a[b])+";";return this.each(function(){this.style.cssText+=";"+d})},index:function(a){return a?this.indexOf(c(a)[0]):this.parent().children().indexOf(this[0])},hasClass:function(a){return e.some.call(this,function(a){return this.test(X(a))},P(a))},addClass:function(a){return this.each(function(b){d=[];var e=X(this),f=V(this,a,b,e);f.split(/\s+/g).forEach(function(a){c(this).hasClass(a)||d.push(a)},this),d.length&&X(this,e+(e?" ":"")+d.join(" "))})},removeClass:function(b){return this.each(function(c){if(b===a)return X(this,"");d=X(this),V(this,b,c,d).split(/\s+/g).forEach(function(a){d=d.replace(P(a)," ")}),X(this,d.trim())})},toggleClass:function(b,d){return this.each(function(e){var f=c(this),g=V(this,b,e,X(this));g.split(/\s+/g).forEach(function(b){(d===a?!f.hasClass(b):d)?f.addClass(b):f.removeClass(b)})})},scrollTop:function(){if(!this.length)return;return"scrollTop"in this[0]?this[0].scrollTop:this[0].scrollY},position:function(){if(!this.length)return;var a=this[0],b=this.offsetParent(),d=this.offset(),e=o.test(b[0].nodeName)?{top:0,left:0}:b.offset();return d.top-=parseFloat(c(a).css("margin-top"))||0,d.left-=parseFloat(c(a).css("margin-left"))||0,e.top+=parseFloat(c(b[0]).css("border-top-width"))||0,e.left+=parseFloat(c(b[0]).css("border-left-width"))||0,{top:d.top-e.top,left:d.left-e.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||h.body;while(a&&!o.test(a.nodeName)&&c(a).css("position")=="static")a=a.offsetParent;return a})}},c.fn.detach=c.fn.remove,["width","height"].forEach(function(b){c.fn[b]=function(d){var e,f=this[0],g=b.replace(/./,function(a){return a[0].toUpperCase()});return d===a?G(f)?f["inner"+g]:H(f)?f.documentElement["offset"+g]:(e=this.offset())&&e[b]:this.each(function(a){f=c(this),f.css(b,V(this,d,a,f[b]()))})}}),q.forEach(function(a,b){var d=b%2;c.fn[a]=function(){var a,e=c.map(arguments,function(b){return a=E(b),a=="object"||a=="array"||b==null?b:A.fragment(b)}),f,g=this.length>1;return e.length<1?this:this.each(function(a,h){f=d?h:h.parentNode,h=b==0?h.nextSibling:b==1?h.firstChild:b==2?h:null,e.forEach(function(a){if(g)a=a.cloneNode(!0);else if(!f)return c(a).remove();Z(f.insertBefore(a,h),function(a){a.nodeName!=null&&a.nodeName.toUpperCase()==="SCRIPT"&&(!a.type||a.type==="text/javascript")&&!a.src&&window.eval.call(window,a.innerHTML)})})})},c.fn[d?a+"To":"insert"+(b?"Before":"After")]=function(b){return c(b)[a](this),this}}),A.Z.prototype=c.fn,A.uniq=C,A.deserializeValue=Y,c.zepto=A,c}();window.Zepto=Zepto,"$"in window||(window.$=Zepto),function(a){function b(a){var b=this.os={},c=this.browser={},d=a.match(/WebKit\/([\d.]+)/),e=a.match(/(Android)\s+([\d.]+)/),f=a.match(/(iPad).*OS\s([\d_]+)/),g=!f&&a.match(/(iPhone\sOS)\s([\d_]+)/),h=a.match(/(webOS|hpwOS)[\s\/]([\d.]+)/),i=h&&a.match(/TouchPad/),j=a.match(/Kindle\/([\d.]+)/),k=a.match(/Silk\/([\d._]+)/),l=a.match(/(BlackBerry).*Version\/([\d.]+)/),m=a.match(/(BB10).*Version\/([\d.]+)/),n=a.match(/(RIM\sTablet\sOS)\s([\d.]+)/),o=a.match(/PlayBook/),p=a.match(/Chrome\/([\d.]+)/)||a.match(/CriOS\/([\d.]+)/),q=a.match(/Firefox\/([\d.]+)/);if(c.webkit=!!d)c.version=d[1];e&&(b.android=!0,b.version=e[2]),g&&(b.ios=b.iphone=!0,b.version=g[2].replace(/_/g,".")),f&&(b.ios=b.ipad=!0,b.version=f[2].replace(/_/g,".")),h&&(b.webos=!0,b.version=h[2]),i&&(b.touchpad=!0),l&&(b.blackberry=!0,b.version=l[2]),m&&(b.bb10=!0,b.version=m[2]),n&&(b.rimtabletos=!0,b.version=n[2]),o&&(c.playbook=!0),j&&(b.kindle=!0,b.version=j[1]),k&&(c.silk=!0,c.version=k[1]),!k&&b.android&&a.match(/Kindle Fire/)&&(c.silk=!0),p&&(c.chrome=!0,c.version=p[1]),q&&(c.firefox=!0,c.version=q[1]),b.tablet=!!(f||o||e&&!a.match(/Mobile/)||q&&a.match(/Tablet/)),b.phone=!b.tablet&&!!(e||g||h||l||m||p&&a.match(/Android/)||p&&a.match(/CriOS\/([\d.]+)/)||q&&a.match(/Mobile/))}b.call(a,navigator.userAgent),a.__detect=b}(Zepto),function(a){function g(a){return a._zid||(a._zid=d++)}function h(a,b,d,e){b=i(b);if(b.ns)var f=j(b.ns);return(c[g(a)]||[]).filter(function(a){return a&&(!b.e||a.e==b.e)&&(!b.ns||f.test(a.ns))&&(!d||g(a.fn)===g(d))&&(!e||a.sel==e)})}function i(a){var b=(""+a).split(".");return{e:b[0],ns:b.slice(1).sort().join(" ")}}function j(a){return new RegExp("(?:^| )"+a.replace(" "," .* ?")+"(?: |$)")}function k(b,c,d){a.type(b)!="string"?a.each(b,d):b.split(/\s/).forEach(function(a){d(a,c)})}function l(a,b){return a.del&&(a.e=="focus"||a.e=="blur")||!!b}function m(a){return f[a]||a}function n(b,d,e,h,j,n){var o=g(b),p=c[o]||(c[o]=[]);k(d,e,function(c,d){var e=i(c);e.fn=d,e.sel=h,e.e in f&&(d=function(b){var c=b.relatedTarget;if(!c||c!==this&&!a.contains(this,c))return e.fn.apply(this,arguments)}),e.del=j&&j(d,c);var g=e.del||d;e.proxy=function(a){var c=g.apply(b,[a].concat(a.data));return c===!1&&(a.preventDefault(),a.stopPropagation()),c},e.i=p.length,p.push(e),b.addEventListener(m(e.e),e.proxy,l(e,n))})}function o(a,b,d,e,f){var i=g(a);k(b||"",d,function(b,d){h(a,b,d,e).forEach(function(b){delete c[i][b.i],a.removeEventListener(m(b.e),b.proxy,l(b,f))})})}function t(b){var c,d={originalEvent:b};for(c in b)!r.test(c)&&b[c]!==undefined&&(d[c]=b[c]);return a.each(s,function(a,c){d[a]=function(){return this[c]=p,b[a].apply(b,arguments)},d[c]=q}),d}function u(a){if(!("defaultPrevented"in a)){a.defaultPrevented=!1;var b=a.preventDefault;a.preventDefault=function(){this.defaultPrevented=!0,b.call(this)}}}var b=a.zepto.qsa,c={},d=1,e={},f={mouseenter:"mouseover",mouseleave:"mouseout"};e.click=e.mousedown=e.mouseup=e.mousemove="MouseEvents",a.event={add:n,remove:o},a.proxy=function(b,c){if(a.isFunction(b)){var d=function(){return b.apply(c,arguments)};return d._zid=g(b),d}if(typeof c=="string")return a.proxy(b[c],b);throw new TypeError("expected function")},a.fn.bind=function(a,b){return this.each(function(){n(this,a,b)})},a.fn.unbind=function(a,b){return this.each(function(){o(this,a,b)})},a.fn.one=function(a,b){return this.each(function(c,d){n(this,a,b,null,function(a,b){return function(){var c=a.apply(d,arguments);return o(d,b,a),c}})})};var p=function(){return!0},q=function(){return!1},r=/^([A-Z]|layer[XY]$)/,s={preventDefault:"isDefaultPrevented",stopImmediatePropagation:"isImmediatePropagationStopped",stopPropagation:"isPropagationStopped"};a.fn.delegate=function(b,c,d){return this.each(function(e,f){n(f,c,d,b,function(c){return function(d){var e,g=a(d.target).closest(b,f).get(0);if(g)return e=a.extend(t(d),{currentTarget:g,liveFired:f}),c.apply(g,[e].concat([].slice.call(arguments,1)))}})})},a.fn.undelegate=function(a,b,c){return this.each(function(){o(this,b,c,a)})},a.fn.live=function(b,c){return a(document.body).delegate(this.selector,b,c),this},a.fn.die=function(b,c){return a(document.body).undelegate(this.selector,b,c),this},a.fn.on=function(b,c,d){return!c||a.isFunction(c)?this.bind(b,c||d):this.delegate(c,b,d)},a.fn.off=function(b,c,d){return!c||a.isFunction(c)?this.unbind(b,c||d):this.undelegate(c,b,d)},a.fn.trigger=function(b,c){if(typeof b=="string"||a.isPlainObject(b))b=a.Event(b);return u(b),b.data=c,this.each(function(){"dispatchEvent"in this&&this.dispatchEvent(b)})},a.fn.triggerHandler=function(b,c){var d,e;return this.each(function(f,g){d=t(typeof b=="string"?a.Event(b):b),d.data=c,d.target=g,a.each(h(g,b.type||b),function(a,b){e=b.proxy(d);if(d.isImmediatePropagationStopped())return!1})}),e},"focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select keydown keypress keyup error".split(" ").forEach(function(b){a.fn[b]=function(a){return a?this.bind(b,a):this.trigger(b)}}),["focus","blur"].forEach(function(b){a.fn[b]=function(a){return a?this.bind(b,a):this.each(function(){try{this[b]()}catch(a){}}),this}}),a.Event=function(a,b){typeof a!="string"&&(b=a,a=b.type);var c=document.createEvent(e[a]||"Events"),d=!0;if(b)for(var f in b)f=="bubbles"?d=!!b[f]:c[f]=b[f];return c.initEvent(a,d,!0,null,null,null,null,null,null,null,null,null,null,null,null),c.isDefaultPrevented=function(){return this.defaultPrevented},c}}(Zepto),function($){function triggerAndReturn(a,b,c){var d=$.Event(b);return $(a).trigger(d,c),!d.defaultPrevented}function triggerGlobal(a,b,c,d){if(a.global)return triggerAndReturn(b||document,c,d)}function ajaxStart(a){a.global&&$.active++===0&&triggerGlobal(a,null,"ajaxStart")}function ajaxStop(a){a.global&&!--$.active&&triggerGlobal(a,null,"ajaxStop")}function ajaxBeforeSend(a,b){var c=b.context;if(b.beforeSend.call(c,a,b)===!1||triggerGlobal(b,c,"ajaxBeforeSend",[a,b])===!1)return!1;triggerGlobal(b,c,"ajaxSend",[a,b])}function ajaxSuccess(a,b,c){var d=c.context,e="success";c.success.call(d,a,e,b),triggerGlobal(c,d,"ajaxSuccess",[b,c,a]),ajaxComplete(e,b,c)}function ajaxError(a,b,c,d){var e=d.context;d.error.call(e,c,b,a),triggerGlobal(d,e,"ajaxError",[c,d,a]),ajaxComplete(b,c,d)}function ajaxComplete(a,b,c){var d=c.context;c.complete.call(d,b,a),triggerGlobal(c,d,"ajaxComplete",[b,c]),ajaxStop(c)}function empty(){}function mimeToDataType(a){return a&&(a=a.split(";",2)[0]),a&&(a==htmlType?"html":a==jsonType?"json":scriptTypeRE.test(a)?"script":xmlTypeRE.test(a)&&"xml")||"text"}function appendQuery(a,b){return(a+"&"+b).replace(/[&?]{1,2}/,"?")}function serializeData(a){a.processData&&a.data&&$.type(a.data)!="string"&&(a.data=$.param(a.data,a.traditional)),a.data&&(!a.type||a.type.toUpperCase()=="GET")&&(a.url=appendQuery(a.url,a.data))}function parseArguments(a,b,c,d){var e=!$.isFunction(b);return{url:a,data:e?b:undefined,success:e?$.isFunction(c)?c:undefined:b,dataType:e?d||c:c}}function serialize(a,b,c,d){var e,f=$.isArray(b);$.each(b,function(b,g){e=$.type(g),d&&(b=c?d:d+"["+(f?"":b)+"]"),!d&&f?a.add(g.name,g.value):e=="array"||!c&&e=="object"?serialize(a,g,c,b):a.add(b,g)})}var jsonpID=0,document=window.document,key,name,rscript=/)<[^<]*)*<\/script>/gi,scriptTypeRE=/^(?:text|application)\/javascript/i,xmlTypeRE=/^(?:text|application)\/xml/i,jsonType="application/json",htmlType="text/html",blankRE=/^\s*$/;$.active=0,$.ajaxJSONP=function(a){if("type"in a){var b="jsonp"+ ++jsonpID,c=document.createElement("script"),d=function(){clearTimeout(g),$(c).remove(),delete window[b]},e=function(c){d();if(!c||c=="timeout")window[b]=empty;ajaxError(null,c||"abort",f,a)},f={abort:e},g;return ajaxBeforeSend(f,a)===!1?(e("abort"),!1):(window[b]=function(b){d(),ajaxSuccess(b,f,a)},c.onerror=function(){e("error")},c.src=a.url.replace(/=\?/,"="+b),$("head").append(c),a.timeout>0&&(g=setTimeout(function(){e("timeout")},a.timeout)),f)}return $.ajax(a)},$.ajaxSettings={type:"GET",beforeSend:empty,success:empty,error:empty,complete:empty,context:null,global:!0,xhr:function(){return new window.XMLHttpRequest},accepts:{script:"text/javascript, application/javascript",json:jsonType,xml:"application/xml, text/xml",html:htmlType,text:"text/plain"},crossDomain:!1,timeout:0,processData:!0,cache:!0},$.ajax=function(options){var settings=$.extend({},options||{});for(key in $.ajaxSettings)settings[key]===undefined&&(settings[key]=$.ajaxSettings[key]);ajaxStart(settings),settings.crossDomain||(settings.crossDomain=/^([\w-]+:)?\/\/([^\/]+)/.test(settings.url)&&RegExp.$2!=window.location.host),settings.url||(settings.url=window.location.toString()),serializeData(settings),settings.cache===!1&&(settings.url=appendQuery(settings.url,"_="+Date.now()));var dataType=settings.dataType,hasPlaceholder=/=\?/.test(settings.url);if(dataType=="jsonp"||hasPlaceholder)return hasPlaceholder||(settings.url=appendQuery(settings.url,"callback=?")),$.ajaxJSONP(settings);var mime=settings.accepts[dataType],baseHeaders={},protocol=/^([\w-]+:)\/\//.test(settings.url)?RegExp.$1:window.location.protocol,xhr=settings.xhr(),abortTimeout;settings.crossDomain||(baseHeaders["X-Requested-With"]="XMLHttpRequest"),mime&&(baseHeaders.Accept=mime,mime.indexOf(",")>-1&&(mime=mime.split(",",2)[0]),xhr.overrideMimeType&&xhr.overrideMimeType(mime));if(settings.contentType||settings.contentType!==!1&&settings.data&&settings.type.toUpperCase()!="GET")baseHeaders["Content-Type"]=settings.contentType||"application/x-www-form-urlencoded";settings.headers=$.extend(baseHeaders,settings.headers||{}),xhr.onreadystatechange=function(){if(xhr.readyState==4){xhr.onreadystatechange=empty,clearTimeout(abortTimeout);var result,error=!1;if(xhr.status>=200&&xhr.status<300||xhr.status==304||xhr.status==0&&protocol=="file:"){dataType=dataType||mimeToDataType(xhr.getResponseHeader("content-type")),result=xhr.responseText;try{dataType=="script"?(1,eval)(result):dataType=="xml"?result=xhr.responseXML:dataType=="json"&&(result=blankRE.test(result)?null:$.parseJSON(result))}catch(e){error=e}error?ajaxError(error,"parsererror",xhr,settings):ajaxSuccess(result,xhr,settings)}else ajaxError(null,xhr.status?"error":"abort",xhr,settings)}};var async="async"in settings?settings.async:!0;xhr.open(settings.type,settings.url,async);for(name in settings.headers)xhr.setRequestHeader(name,settings.headers[name]);return ajaxBeforeSend(xhr,settings)===!1?(xhr.abort(),!1):(settings.timeout>0&&(abortTimeout=setTimeout(function(){xhr.onreadystatechange=empty,xhr.abort(),ajaxError(null,"timeout",xhr,settings)},settings.timeout)),xhr.send(settings.data?settings.data:null),xhr)},$.get=function(a,b,c,d){return $.ajax(parseArguments.apply(null,arguments))},$.post=function(a,b,c,d){var e=parseArguments.apply(null,arguments);return e.type="POST",$.ajax(e)},$.getJSON=function(a,b,c){var d=parseArguments.apply(null,arguments);return d.dataType="json",$.ajax(d)},$.fn.load=function(a,b,c){if(!this.length)return this;var d=this,e=a.split(/\s/),f,g=parseArguments(a,b,c),h=g.success;return e.length>1&&(g.url=e[0],f=e[1]),g.success=function(a){d.html(f?$("
").html(a.replace(rscript,"")).find(f):a),h&&h.apply(d,arguments)},$.ajax(g),this};var escape=encodeURIComponent;$.param=function(a,b){var c=[];return c.add=function(a,b){this.push(escape(a)+"="+escape(b))},serialize(c,a,b),c.join("&").replace(/%20/g,"+")}}(Zepto),function(a){a.fn.serializeArray=function(){var b=[],c;return a(Array.prototype.slice.call(this.get(0).elements)).each(function(){c=a(this);var d=c.attr("type");this.nodeName.toLowerCase()!="fieldset"&&!this.disabled&&d!="submit"&&d!="reset"&&d!="button"&&(d!="radio"&&d!="checkbox"||this.checked)&&b.push({name:c.attr("name"),value:c.val()})}),b},a.fn.serialize=function(){var a=[];return this.serializeArray().forEach(function(b){a.push(encodeURIComponent(b.name)+"="+encodeURIComponent(b.value))}),a.join("&")},a.fn.submit=function(b){if(b)this.bind("submit",b);else if(this.length){var c=a.Event("submit");this.eq(0).trigger(c),c.defaultPrevented||this.get(0).submit()}return this}}(Zepto),function(a,b){function s(a){return t(a.replace(/([a-z])([A-Z])/,"$1-$2"))}function t(a){return a.toLowerCase()}function u(a){return d?d+a:t(a)}var c="",d,e,f,g={Webkit:"webkit",Moz:"",O:"o",ms:"MS"},h=window.document,i=h.createElement("div"),j=/^((translate|rotate|scale)(X|Y|Z|3d)?|matrix(3d)?|perspective|skew(X|Y)?)$/i,k,l,m,n,o,p,q,r={};a.each(g,function(a,e){if(i.style[a+"TransitionProperty"]!==b)return c="-"+t(a)+"-",d=e,!1}),k=c+"transform",r[l=c+"transition-property"]=r[m=c+"transition-duration"]=r[n=c+"transition-timing-function"]=r[o=c+"animation-name"]=r[p=c+"animation-duration"]=r[q=c+"animation-timing-function"]="",a.fx={off:d===b&&i.style.transitionProperty===b,speeds:{_default:400,fast:200,slow:600},cssPrefix:c,transitionEnd:u("TransitionEnd"),animationEnd:u("AnimationEnd")},a.fn.animate=function(b,c,d,e){return a.isPlainObject(c)&&(d=c.easing,e=c.complete,c=c.duration),c&&(c=(typeof c=="number"?c:a.fx.speeds[c]||a.fx.speeds._default)/1e3),this.anim(b,c,d,e)},a.fn.anim=function(c,d,e,f){var g,h={},i,t="",u=this,v,w=a.fx.transitionEnd;d===b&&(d=.4),a.fx.off&&(d=0);if(typeof c=="string")h[o]=c,h[p]=d+"s",h[q]=e||"linear",w=a.fx.animationEnd;else{i=[];for(g in c)j.test(g)?t+=g+"("+c[g]+") ":(h[g]=c[g],i.push(s(g)));t&&(h[k]=t,i.push(k)),d>0&&typeof c=="object"&&(h[l]=i.join(", "),h[m]=d+"s",h[n]=e||"linear")}return v=function(b){if(typeof b!="undefined"){if(b.target!==b.currentTarget)return;a(b.target).unbind(w,v)}a(this).css(r),f&&f.call(this)},d>0&&this.bind(w,v),this.size()&&this.get(0).clientLeft,this.css(h),d<=0&&setTimeout(function(){u.each(function(){v.call(this)})},0),this},i=null}(Zepto) diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/TimeCheck/TimeCheck.ino b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/TimeCheck/TimeCheck.ino new file mode 100644 index 000000000..0403aa49a --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/TimeCheck/TimeCheck.ino @@ -0,0 +1,88 @@ +/* + Time Check + + Gets the time from Linux via Bridge then parses out hours, + minutes and seconds using a YunShield/Yún. + + created 27 May 2013 + modified 21 June 2013 + By Tom Igoe + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/TimeCheck + + */ + + +#include + +Process date; // process used to get the date +int hours, minutes, seconds; // for the results +int lastSecond = -1; // need an impossible value for comparison + +void setup() { + Bridge.begin(); // initialize Bridge + SerialUSB.begin(9600); // initialize serial + + while (!Serial); // wait for Serial Monitor to open + SerialUSB.println("Time Check"); // Title of sketch + + // run an initial date process. Should return: + // hh:mm:ss : + if (!date.running()) { + date.begin("date"); + date.addParameter("+%T"); + date.run(); + } +} + +void loop() { + + if (lastSecond != seconds) { // if a second has passed + // print the time: + if (hours <= 9) { + SerialUSB.print("0"); // adjust for 0-9 + } + SerialUSB.print(hours); + SerialUSB.print(":"); + if (minutes <= 9) { + SerialUSB.print("0"); // adjust for 0-9 + } + SerialUSB.print(minutes); + SerialUSB.print(":"); + if (seconds <= 9) { + SerialUSB.print("0"); // adjust for 0-9 + } + SerialUSB.println(seconds); + + // restart the date process: + if (!date.running()) { + date.begin("date"); + date.addParameter("+%T"); + date.run(); + } + } + + //if there's a result from the date process, parse it: + while (date.available() > 0) { + // get the result of the date process (should be hh:mm:ss): + String timeString = date.readString(); + + // find the colons: + int firstColon = timeString.indexOf(":"); + int secondColon = timeString.lastIndexOf(":"); + + // get the substrings for hour, minute second: + String hourString = timeString.substring(0, firstColon); + String minString = timeString.substring(firstColon + 1, secondColon); + String secString = timeString.substring(secondColon + 1); + + // convert to ints,saving the previous second: + hours = hourString.toInt(); + minutes = minString.toInt(); + lastSecond = seconds; // save to do a time comparison + seconds = secString.toInt(); + } + +} diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/WiFiStatus/WiFiStatus.ino b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/WiFiStatus/WiFiStatus.ino new file mode 100644 index 000000000..198761ba2 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/WiFiStatus/WiFiStatus.ino @@ -0,0 +1,51 @@ +/* + WiFi Status + + This sketch runs a script called "pretty-wifi-info.lua" + installed on your Yún in folder /usr/bin. + It prints information about the status of your wifi connection. + + It uses Serial to print, so you need to connect your YunShield/Yún to your + computer using a USB cable and select the appropriate port from + the Port menu + + created 18 June 2013 + By Federico Fissore + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/YunWiFiStatus + + */ + +#include + +void setup() { + SerialUSB.begin(9600); // initialize serial communication + while (!SerialUSB); // do nothing until the serial monitor is opened + + SerialUSB.println("Starting bridge...\n"); + pinMode(13, OUTPUT); + digitalWrite(13, LOW); + Bridge.begin(); // make contact with the linux processor + digitalWrite(13, HIGH); // Led on pin 13 turns on when the bridge is ready + + delay(2000); // wait 2 seconds +} + +void loop() { + Process wifiCheck; // initialize a new process + + wifiCheck.runShellCommand("/usr/bin/pretty-wifi-info.lua"); // command you want to run + + // while there's any characters coming back from the + // process, print them to the serial monitor: + while (wifiCheck.available() > 0) { + char c = wifiCheck.read(); + SerialUSB.print(c); + } + + SerialUSB.println(); + + delay(5000); +} diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/YunFirstConfig/YunFirstConfig.ino b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/YunFirstConfig/YunFirstConfig.ino new file mode 100644 index 000000000..72bf9e00b --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/YunFirstConfig/YunFirstConfig.ino @@ -0,0 +1,328 @@ + +/* + Arduino Yún First configuration sketch + + Configures the YunShield/Yún WiFi and infos via the Bridge + Works correctly if Line Ending is set as "NewLine" + If your board has two USB ports, use the Native one + + The circuit: + Arduino YunShield + (or any Yun model with firmware > 1.6.1) + + created March 2016 + by Arduino LLC + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/YunFirstConfig +*/ + +#include + +#define MAX_WIFI_LIST 10 + +String networks[MAX_WIFI_LIST]; +String yunName; +String yunPassword; + +void setup() { + SERIAL_PORT_USBVIRTUAL.begin(9600); // initialize serial communication + while (!SERIAL_PORT_USBVIRTUAL); // do nothing until the serial monitor is opened + + SERIAL_PORT_USBVIRTUAL.println(F("Hi! Nice to see you!")); + SERIAL_PORT_USBVIRTUAL.println(F("I'm your YunShield assistant sketch")); + SERIAL_PORT_USBVIRTUAL.println(F("I'll help you configuring your Yun in a matter of minutes")); + + SERIAL_PORT_USBVIRTUAL.println(F("Let's start by communicating with the Linux processor")); + SERIAL_PORT_USBVIRTUAL.println(F("When LED (L13) will light up we'll be ready to go!")); + SERIAL_PORT_USBVIRTUAL.println(F("Waiting...")); + SERIAL_PORT_USBVIRTUAL.println(F("(in the meanwhile, if you are using the IDE's serial monitor, make sure that it's configured to send a \"Newline\")\n")); + pinMode(13, OUTPUT); + digitalWrite(13, LOW); + Bridge.begin(); // make contact with the linux processor + digitalWrite(13, HIGH); // Led on pin 13 turns on when the bridge is ready + + // Recover if the board is in AP mode - unused + Process wifiList; + bool master = false; + wifiList.runShellCommand(F("iwinfo | grep \"Mode: Master\"")); + while (wifiList.available() > 0) { + wifiList.read(); + master = true; + } + + // Get the list of reachable networks + wifiList.runShellCommand(F("iwinfo wlan0 scan | grep ESSID | cut -d\"\\\"\" -f2")); + + uint8_t num_networks = 0; + uint8_t i = 0; + char c; + bool dropNet = false; + + networks[0].reserve(32); + + while (wifiList.available() > 0) { + c = wifiList.read(); + if (c != '\n') { + networks[i] += c; + } else { + // check if we already found networks[i] and eventually drop it + for (uint8_t s = 0; s < i; s++) { + if (networks[i].equals(networks[s])) { + dropNet = true; + } + } + if (i <= MAX_WIFI_LIST && dropNet == false) { + networks[i++].reserve(32); + } else { + dropNet = false; + networks[i]=""; + } + } + } + + num_networks = i; + + String encryption; + String password; + int chose = 0; + + // If networks number is 0, start manual configuration + if (num_networks == 0) { + SERIAL_PORT_USBVIRTUAL.println(F("Oops, it seems that you have no WiFi network available")); + SERIAL_PORT_USBVIRTUAL.println(F("Let's configure it manually")); + SERIAL_PORT_USBVIRTUAL.println(F("SSID of the network you want to connect to: ")); + networks[0] = getUserInput(networks[0], false); + SERIAL_PORT_USBVIRTUAL.println(F("Password for the network you want to connect to: ")); + password = getUserInput(password, true); + SERIAL_PORT_USBVIRTUAL.print(F("Encryption (eg WPA, WPA2, WEP): ")); + encryption = getUserInput(encryption, false); + } else { + // else print them prepending a number + SERIAL_PORT_USBVIRTUAL.print(F("It looks like you have ")); + SERIAL_PORT_USBVIRTUAL.print(num_networks); + SERIAL_PORT_USBVIRTUAL.println(F(" networks around you ")); + SERIAL_PORT_USBVIRTUAL.println(F("Which one do you want to connect to?\n")); + for (i = 0; i < num_networks && i < MAX_WIFI_LIST; i++) { + SERIAL_PORT_USBVIRTUAL.print(i); + SERIAL_PORT_USBVIRTUAL.println(") " + networks[i]); + } + String selection; + selection = getUserInput(selection, false); + chose = atoi(selection.c_str()); + } + + // Extract the selected network security + bool openNet = false; + wifiList.runShellCommand("iwinfo wlan0 scan | grep \"" + networks[chose] + "\" -A5 | grep Encryption | cut -f2 -d\":\""); + while (wifiList.available() > 0) { + c = wifiList.read(); + encryption += c; + } + + if (encryption.indexOf("none") >= 0) { + openNet = true; + encryption = "none"; + } + if (encryption.indexOf("WPA2") >= 0) { + encryption = "psk2"; + } + if (encryption.indexOf("WPA") >= 0) { + encryption = "psk"; + } + if (encryption.indexOf("WEP") >= 0) { + encryption = "wep"; + } + + if (openNet == false && password.length() == 0) { + SERIAL_PORT_USBVIRTUAL.print(F("It looks like you need a password to connect to ")); + SERIAL_PORT_USBVIRTUAL.println(networks[chose]); + SERIAL_PORT_USBVIRTUAL.print(F("Write it here: ")); + password = getUserInput(password, true); + } + + // Change hostname/root password + SERIAL_PORT_USBVIRTUAL.println(F("We are almost done! Give a name and a password to your Yun")); + SERIAL_PORT_USBVIRTUAL.print(F("Name: ")); + yunName = getUserInput(yunName, false); + SERIAL_PORT_USBVIRTUAL.print(F("Password: ")); + yunPassword = getUserInput(yunPassword, true); + + // Select a country code + String countryCode; + SERIAL_PORT_USBVIRTUAL.println(F("One last question: where do you live?")); + SERIAL_PORT_USBVIRTUAL.print(F("Insert a two letters county code (eg IT, US, DE): ")); + countryCode = getUserInput(countryCode, false); + + yunName.trim(); + yunPassword.trim(); + networks[chose].trim(); + password.trim(); + countryCode.trim(); + + // Configure the Yun with user provided strings + wifiConfig(yunName, yunPassword, networks[chose], password, "YUN" + yunName + "AP", countryCode, encryption); + + SERIAL_PORT_USBVIRTUAL.print(F("Waiting for the Yun to connect to the network")); +} + +bool Connected = false; +bool serialTerminalMode = false; +int runs = 0; + +void loop() { + if (!serialTerminalMode) { + String resultStr = ""; + + if (!Connected) { + SERIAL_PORT_USBVIRTUAL.print("."); + runs++; + } + + // If it takes more than 20 seconds to connect, stop trying + if (runs > 20) { + SERIAL_PORT_USBVIRTUAL.println(""); + SERIAL_PORT_USBVIRTUAL.println(F("We couldn't connect to the network.")); + SERIAL_PORT_USBVIRTUAL.println(F("Restart the board if you want to execute the wizard again")); + resultStr = getUserInput(resultStr, false); + } + + // Check if we have an IP address + Process wifiCheck; + wifiCheck.runShellCommand(F("/usr/bin/pretty-wifi-info.lua | grep \"IP address\" | cut -f2 -d\":\" | cut -f1 -d\"/\"" )); // command you want to run + while (wifiCheck.available() > 0) { + char c = wifiCheck.read(); + resultStr += c; + } + + delay(1000); + + if (resultStr != "") { + // We got an IP, freeze the loop, display the value and "spawn" a serial terminal + Connected = true; + resultStr.trim(); + SERIAL_PORT_USBVIRTUAL.println(""); + SERIAL_PORT_USBVIRTUAL.print(F("\nGreat! You can now reach your Yun from a browser typing http://")); + SERIAL_PORT_USBVIRTUAL.println(resultStr); + SERIAL_PORT_USBVIRTUAL.print(F("Press 'Enter' key twice to start a serial terminal")); + resultStr = getUserInput(resultStr, false); + serialTerminalMode = true; + //startSerialTerminal(); + SERIAL_PORT_HARDWARE.write((uint8_t *)"\xff\0\0\x05XXXXX\x7f\xf9", 11); // send "bridge shutdown" command + delay(100); + SERIAL_PORT_HARDWARE.println("\nreset\n\n"); + SERIAL_PORT_HARDWARE.flush(); + SERIAL_PORT_HARDWARE.println("\nreset\n\n"); + SERIAL_PORT_HARDWARE.write((uint8_t *)"\n", 1); + } + + } else { + loopSerialTerminal(); + } +} + +String getUserInput(String out, bool obfuscated) { + /* + while (SerialUSB.available() <= 0) {} + while (SerialUSB.available() > 0) { + char c = SerialUSB.read(); + out += c; + } + return out; + */ + while (SERIAL_PORT_USBVIRTUAL.available() <= 0) {} + while (1) { + char c = SERIAL_PORT_USBVIRTUAL.read(); + if (c == '\n' || c == '\r') + break; + else { + if (c != -1) { + out += c; + if (obfuscated) + SERIAL_PORT_USBVIRTUAL.print("*"); + else + SERIAL_PORT_USBVIRTUAL.print(c); + } + } + } + SERIAL_PORT_USBVIRTUAL.println(""); + return out; +} + +void wifiConfig(String yunName, String yunPsw, String wifissid, String wifipsw, String wifiAPname, String countryCode, String encryption) { + Process p; + + p.runShellCommand("blink-start 100"); //start the blue blink + + p.runShellCommand("hostname " + yunName); //change the current hostname + p.runShellCommand("uci set system.@system[0].hostname='" + yunName + "'"); //change teh hostname in uci + + p.runShellCommand("uci set arduino.@arduino[0].access_point_wifi_name='" + wifiAPname + "'"); + + //this block resets the wifi psw + p.runShellCommand("uci set wireless.@wifi-iface[0].encryption='" + encryption + "'"); + p.runShellCommand("uci set wireless.@wifi-iface[0].mode='sta'\n"); + p.runShellCommand("uci set wireless.@wifi-iface[0].ssid='" + wifissid + "'"); + p.runShellCommand("uci set wireless.@wifi-iface[0].key='" + wifipsw + "'"); + p.runShellCommand("uci set wireless.radio0.channel='auto'"); + p.runShellCommand("uci set wireless.radio0.country='" + countryCode + "'"); + p.runShellCommand("uci delete network.lan.ipaddr"); + p.runShellCommand("uci delete network.lan.netmask"); + p.runShellCommand("uci set network.lan.proto='dhcp'"); + + p.runShellCommand("echo -e \"" + yunPsw + "\n" + yunPsw + "\" | passwd root"); //change the passwors + p.runShellCommand("uci commit"); //save the mods done via UCI + p.runShellCommand("blink-stop"); //start the blue blink + + p.runShellCommand("wifi "); +} + +long linuxBaud = 250000; + +void startSerialTerminal() { + SERIAL_PORT_USBVIRTUAL.begin(115200); // open serial connection via USB-Serial + SERIAL_PORT_HARDWARE.begin(linuxBaud); // open serial connection to Linux +} + +boolean commandMode = false; +void loopSerialTerminal() { + // copy from USB-CDC to UART + int c = SERIAL_PORT_USBVIRTUAL.read(); // read from USB-CDC + if (c != -1) { // got anything? + if (commandMode == false) { // if we aren't in command mode... + if (c == '~') { // Tilde '~' key pressed? + commandMode = true; // enter in command mode + } else { + SERIAL_PORT_HARDWARE.write(c); // otherwise write char to UART + } + } else { // if we are in command mode... + if (c == '0') { // '0' key pressed? + SERIAL_PORT_HARDWARE.begin(57600); // set speed to 57600 + SERIAL_PORT_USBVIRTUAL.println("Speed set to 57600"); + } else if (c == '1') { // '1' key pressed? + SERIAL_PORT_HARDWARE.begin(115200); // set speed to 115200 + SERIAL_PORT_USBVIRTUAL.println("Speed set to 115200"); + } else if (c == '2') { // '2' key pressed? + SERIAL_PORT_HARDWARE.begin(250000); // set speed to 250000 + SERIAL_PORT_USBVIRTUAL.println("Speed set to 250000"); + } else if (c == '3') { // '3' key pressed? + SERIAL_PORT_HARDWARE.begin(500000); // set speed to 500000 + SERIAL_PORT_USBVIRTUAL.println("Speed set to 500000"); + } else if (c == '~') { // '~` key pressed? + SERIAL_PORT_HARDWARE.write((uint8_t *)"\xff\0\0\x05XXXXX\x7f\xf9", 11); // send "bridge shutdown" command + SERIAL_PORT_USBVIRTUAL.println("Sending bridge's shutdown command"); + } else { // any other key pressed? + SERIAL_PORT_HARDWARE.write('~'); // write '~' to UART + SERIAL_PORT_HARDWARE.write(c); // write char to UART + } + commandMode = false; // in all cases exit from command mode + } + } + + // copy from UART to USB-CDC + c = SERIAL_PORT_HARDWARE.read(); // read from UART + if (c != -1) { // got anything? + SERIAL_PORT_USBVIRTUAL.write(c); // write to USB-CDC + } +} diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/YunSerialTerminal/YunSerialTerminal.ino b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/YunSerialTerminal/YunSerialTerminal.ino new file mode 100644 index 000000000..641c1e9f0 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/examples/YunSerialTerminal/YunSerialTerminal.ino @@ -0,0 +1,82 @@ +/* + Arduino Yún USB-to-Serial + + Allows you to use the YunShield/Yún processor as a + serial terminal for the Linux side on the Yún. + + Upload this to a YunShield/Yún via serial (not WiFi) then open + the serial monitor at 115200 to see the boot process of Linux. + You can also use the serial monitor as a basic command line + interface for Linux using this sketch. + + From the serial monitor the following commands can be issued: + + '~' followed by '0' -> Set the UART speed to 57600 baud + '~' followed by '1' -> Set the UART speed to 115200 baud + '~' followed by '2' -> Set the UART speed to 250000 baud + '~' followed by '3' -> Set the UART speed to 500000 baud + '~' followed by '~' -> Sends the bridge's shutdown command to + obtain the console. + + The circuit: + YunShield/Yún + + created March 2013 + by Massimo Banzi + modified by Cristian Maglie + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/YunSerialTerminal + +*/ + +long linuxBaud = 250000; + +void setup() { + SERIAL_PORT_USBVIRTUAL.begin(115200); // open serial connection via USB-Serial + SERIAL_PORT_HARDWARE.begin(linuxBaud); // open serial connection to Linux +} + +boolean commandMode = false; + +void loop() { + // copy from USB-CDC to UART + int c = SERIAL_PORT_USBVIRTUAL.read(); // read from USB-CDC + if (c != -1) { // got anything? + if (commandMode == false) { // if we aren't in command mode... + if (c == '~') { // Tilde '~' key pressed? + commandMode = true; // enter in command mode + } else { + SERIAL_PORT_HARDWARE.write(c); // otherwise write char to UART + } + } else { // if we are in command mode... + if (c == '0') { // '0' key pressed? + SERIAL_PORT_HARDWARE.begin(57600); // set speed to 57600 + SERIAL_PORT_USBVIRTUAL.println("Speed set to 57600"); + } else if (c == '1') { // '1' key pressed? + SERIAL_PORT_HARDWARE.begin(115200); // set speed to 115200 + SERIAL_PORT_USBVIRTUAL.println("Speed set to 115200"); + } else if (c == '2') { // '2' key pressed? + SERIAL_PORT_HARDWARE.begin(250000); // set speed to 250000 + SERIAL_PORT_USBVIRTUAL.println("Speed set to 250000"); + } else if (c == '3') { // '3' key pressed? + SERIAL_PORT_HARDWARE.begin(500000); // set speed to 500000 + SERIAL_PORT_USBVIRTUAL.println("Speed set to 500000"); + } else if (c == '~') { // '~` key pressed? + SERIAL_PORT_HARDWARE.write((uint8_t *)"\xff\0\0\x05XXXXX\x7f\xf9", 11); // send "bridge shutdown" command + SERIAL_PORT_USBVIRTUAL.println("Sending bridge's shutdown command"); + } else { // any other key pressed? + SERIAL_PORT_HARDWARE.write('~'); // write '~' to UART + SERIAL_PORT_HARDWARE.write(c); // write char to UART + } + commandMode = false; // in all cases exit from command mode + } + } + + // copy from UART to USB-CDC + c = SERIAL_PORT_HARDWARE.read(); // read from UART + if (c != -1) { // got anything? + SERIAL_PORT_USBVIRTUAL.write(c); // write to USB-CDC + } +} diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/keywords.txt b/app/testdata/libraries/Bridge_1.6.3/Bridge/keywords.txt new file mode 100644 index 000000000..ef5d5eb7d --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/keywords.txt @@ -0,0 +1,92 @@ +####################################### +# Syntax Coloring Map For Bridge +####################################### + +####################################### +# Class (KEYWORD1) +####################################### + +Bridge KEYWORD1 YunBridgeLibrary +FileIO KEYWORD4 YunFileIOConstructor +FileSystem KEYWORD1 YunFileIOConstructor +Console KEYWORD1 YunConsoleConstructor +Process KEYWORD1 YunProcessConstructor +Mailbox KEYWORD1 YunMailboxConstructor +HttpClient KEYWORD1 YunHttpClientConstructor +YunServer KEYWORD1 YunServerConstructor +YunClient KEYWORD1 YunClientConstructor +BridgeServer KEYWORD1 YunServerConstructor +BridgeClient KEYWORD1 YunClientConstructor +BridgeSSLClient KEYWORD1 YunClientConstructor + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +# methods names in commond +begin KEYWORD2 +end KEYWORD2 +available KEYWORD2 +read KEYWORD2 +peek KEYWORD2 +write KEYWORD2 +flush KEYWORD2 +bool KEYWORD2 + +# Bridge Class +transfer KEYWORD2 +put KEYWORD2 +get KEYWORD2 + +# Console Class +buffer KEYWORD2 +noBuffer KEYWORD2 +connected KEYWORD2 + +# FileIO Class +File KEYWORD2 +BridgeFile KEYWORD2 +seek KEYWORD2 +position KEYWORD2 +size KEYWORD2 +close KEYWORD2 +name KEYWORD2 +isDirectory KEYWORD2 +openNextFile KEYWORD2 +rewindDirectory KEYWORD2 + +# Process Class +addParameter KEYWORD2 +runAsynchronously KEYWORD2 +run KEYWORD2 +running KEYWORD2 +exitValue KEYWORD2 +runShellCommand KEYWORD2 +runShellCommandAsynchronously KEYWORD2 + +# Mailbox Class +readMessage KEYWORD2 +writeMessage KEYWORD2 +writeJSON KEYWORD2 +message Available KEYWORD2 + +# HttpClient Class +getAsynchronously KEYWORD2 +ready KEYWORD2 +getResult KEYWORD2 + +# BridgeServer Class +accept KEYWORD2 +stop KEYWORD2 +connect KEYWORD2 +connectSSL KEYWORD2 +connected KEYWORD2 + + +####################################### +# Constants (LITERAL1) +####################################### + +FILE_READ LITERAL1 +FILE_WRITE LITERAL1 +FILE_APPEND LITERAL1 diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/library.properties b/app/testdata/libraries/Bridge_1.6.3/Bridge/library.properties new file mode 100644 index 000000000..ce642f255 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/library.properties @@ -0,0 +1,10 @@ +name=Bridge +version=1.6.3 +author=Arduino +maintainer=Arduino +sentence=Enables the communication between the Linux processor and the microcontroller. For Arduino/Genuino Yún, Yún Shield and TRE only. +paragraph=The Bridge library feature: access to the shared storage, run and manage linux processes, open a remote console, access to the linux file system, including the SD card, enstablish http clients or servers. +category=Communication +url=http://www.arduino.cc/en/Reference/YunBridgeLibrary +architectures=* +dot_a_linkage=true diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/src/Bridge.cpp b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/Bridge.cpp new file mode 100644 index 000000000..02be3805e --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/Bridge.cpp @@ -0,0 +1,281 @@ +/* + Copyright (c) 2013 Arduino LLC. 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 "Bridge.h" + +BridgeClass::BridgeClass(Stream &_stream) : + index(0), stream(_stream), started(false), max_retries(0) { + // Empty +} + +void BridgeClass::begin() { + if (started) + return; + started = true; + + // Wait for U-boot to finish startup + do { + dropAll(); + delay(1000); + } while (stream.available() > 0); + + while (true) { + // Bridge interrupt: + // - Ask the bridge to close itself + uint8_t quit_cmd[] = {'X', 'X', 'X', 'X', 'X'}; + max_retries = 1; + transfer(quit_cmd, 5); + + // Bridge startup: + // - If the bridge is not running starts it safely + stream.print(CTRL_C); + delay(250); + stream.print(F("\n")); + delay(250); + stream.print(F("\n")); + delay(500); + // Wait for OpenWRT message + // "Press enter to activate console" + stream.print(F("run-bridge\n")); + delay(500); + dropAll(); + + // Reset the brigde to check if it is running + uint8_t cmd[] = {'X', 'X', '1', '0', '0'}; + uint8_t res[4]; + max_retries = 50; + uint16_t l = transfer(cmd, 5, res, 4); + if (l == TRANSFER_TIMEOUT) { + // Bridge didn't start... + // Maybe the board is starting-up? + + // Wait and retry + delay(1000); + continue; + } + if (res[0] != 0) + while (true); + + // Detect bridge version + if (l == 4) { + bridgeVersion = (res[1]-'0')*100 + (res[2]-'0')*10 + (res[3]-'0'); + } else { + // Bridge v1.0.0 didn't send any version info + bridgeVersion = 100; + } + + max_retries = 50; + return; + } +} + +void BridgeClass::put(const char *key, const char *value) { + // TODO: do it in a more efficient way + String cmd = "D"; + uint8_t res[1]; + cmd += key; + cmd += "\xFE"; + cmd += value; + transfer((uint8_t*)cmd.c_str(), cmd.length(), res, 1); +} + +unsigned int BridgeClass::get(const char *key, uint8_t *value, unsigned int maxlen) { + uint8_t cmd[] = {'d'}; + unsigned int l = transfer(cmd, 1, (uint8_t *)key, strlen(key), value, maxlen); + if (l < maxlen) + value[l] = 0; // Zero-terminate string + return l; +} + +#if defined(ARDUINO_ARCH_AVR) +// AVR use an optimized implementation of CRC +#include +#else +// Generic implementation for non-AVR architectures +uint16_t _crc_ccitt_update(uint16_t crc, uint8_t data) +{ + data ^= crc & 0xff; + data ^= data << 4; + return ((((uint16_t)data << 8) | ((crc >> 8) & 0xff)) ^ + (uint8_t)(data >> 4) ^ + ((uint16_t)data << 3)); +} +#endif + +void BridgeClass::crcUpdate(uint8_t c) { + CRC = _crc_ccitt_update(CRC, c); +} + +void BridgeClass::crcReset() { + CRC = 0xFFFF; +} + +void BridgeClass::crcWrite() { + stream.write((char)(CRC >> 8)); + stream.write((char)(CRC & 0xFF)); +} + +bool BridgeClass::crcCheck(uint16_t _CRC) { + return CRC == _CRC; +} + +uint16_t BridgeClass::transfer(const uint8_t *buff1, uint16_t len1, + const uint8_t *buff2, uint16_t len2, + const uint8_t *buff3, uint16_t len3, + uint8_t *rxbuff, uint16_t rxlen) +{ + uint16_t len = len1 + len2 + len3; + uint8_t retries = 0; + for ( ; retries < max_retries; retries++, delay(100), dropAll() /* Delay for retransmission */) { + // Send packet + crcReset(); + stream.write((char)0xFF); // Start of packet (0xFF) + crcUpdate(0xFF); + stream.write((char)index); // Message index + crcUpdate(index); + stream.write((char)((len >> 8) & 0xFF)); // Message length (hi) + crcUpdate((len >> 8) & 0xFF); + stream.write((char)(len & 0xFF)); // Message length (lo) + crcUpdate(len & 0xFF); + for (uint16_t i = 0; i < len1; i++) { // Payload + stream.write((char)buff1[i]); + crcUpdate(buff1[i]); + } + for (uint16_t i = 0; i < len2; i++) { // Payload + stream.write((char)buff2[i]); + crcUpdate(buff2[i]); + } + for (uint16_t i = 0; i < len3; i++) { // Payload + stream.write((char)buff3[i]); + crcUpdate(buff3[i]); + } + crcWrite(); // CRC + + // Wait for ACK in 100ms + if (timedRead(100) != 0xFF) + continue; + crcReset(); + crcUpdate(0xFF); + + // Check packet index + if (timedRead(5) != index) + continue; + crcUpdate(index); + + // Recv len + int lh = timedRead(10); + if (lh < 0) + continue; + crcUpdate(lh); + int ll = timedRead(10); + if (ll < 0) + continue; + crcUpdate(ll); + uint16_t l = lh; + l <<= 8; + l += ll; + + // Recv data + for (uint16_t i = 0; i < l; i++) { + // Cut received data if rxbuffer is too small + if (i >= rxlen) + break; + int c = timedRead(5); + if (c < 0) + continue; + rxbuff[i] = c; + crcUpdate(c); + } + + // Check CRC + int crc_hi = timedRead(5); + if (crc_hi < 0) + continue; + int crc_lo = timedRead(5); + if (crc_lo < 0) + continue; + if (!crcCheck((crc_hi << 8) + crc_lo)) + continue; + + // Increase index + index++; + + // Return bytes received + if (l > rxlen) + return rxlen; + return l; + } + + // Max retries exceeded + return TRANSFER_TIMEOUT; +} + +int BridgeClass::timedRead(unsigned int timeout) { + int c; + unsigned long _startMillis = millis(); + do { + c = stream.read(); + if (c >= 0) return c; + } while (millis() - _startMillis < timeout); + return -1; // -1 indicates timeout +} + +void BridgeClass::dropAll() { + while (stream.available() > 0) { + stream.read(); + } +} + +#if defined(ARDUINO_ARCH_SAM) +#include +#endif + +#if defined(ARDUINO_ARCH_SAM) +void checkForRemoteSketchUpdate(uint8_t pin) { + // The host force pin LOW to signal that a new sketch is coming + pinMode(pin, INPUT_PULLUP); + delay(50); + if (digitalRead(pin) == LOW) { + initiateReset(1); + while (true) + ; // Wait for reset to SAM-BA + } + + // Restore in standard state + pinMode(pin, INPUT); +} +#else +void checkForRemoteSketchUpdate(uint8_t /* pin */) { + // Empty, bootloader is enough. +} +#endif + +// Bridge instance +#if defined(SERIAL_PORT_LINUXBRIDGE) +SerialBridgeClass Bridge(SERIAL_PORT_LINUXBRIDGE); +#elif defined(SERIAL_PORT_HARDWARE) +SerialBridgeClass Bridge(SERIAL_PORT_HARDWARE); +#elif defined(SERIAL_PORT_HARDWARE_OPEN) +SerialBridgeClass Bridge(SERIAL_PORT_HARDWARE_OPEN); +#elif defined(__AVR_ATmega32U4__) // Legacy fallback +// Leonardo variants (where HardwareSerial is Serial1) +SerialBridgeClass Bridge(Serial1); +#else +SerialBridgeClass Bridge(Serial); +#endif + diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/src/Bridge.h b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/Bridge.h new file mode 100644 index 000000000..63361f172 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/Bridge.h @@ -0,0 +1,125 @@ +/* + Copyright (c) 2013 Arduino LLC. 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 BRIDGE_H_ +#define BRIDGE_H_ + +#ifndef BRIDGE_BAUDRATE +#define BRIDGE_BAUDRATE 250000 +#endif + +#include +#include + +class BridgeClass { + public: + BridgeClass(Stream &_stream); + void begin(); + + // Methods to handle key/value datastore + void put(const char *key, const char *value); + void put(const String &key, const String &value) + { + put(key.c_str(), value.c_str()); + } + unsigned int get(const char *key, uint8_t *buff, unsigned int size); + unsigned int get(const char *key, char *value, unsigned int maxlen) + { + return get(key, reinterpret_cast(value), maxlen); + } + + // Trasnfer a frame (with error correction and response) + uint16_t transfer(const uint8_t *buff1, uint16_t len1, + const uint8_t *buff2, uint16_t len2, + const uint8_t *buff3, uint16_t len3, + uint8_t *rxbuff, uint16_t rxlen); + // multiple inline versions of the same function to allow efficient frame concatenation + uint16_t transfer(const uint8_t *buff1, uint16_t len1) + { + return transfer(buff1, len1, NULL, 0); + } + uint16_t transfer(const uint8_t *buff1, uint16_t len1, + uint8_t *rxbuff, uint16_t rxlen) + { + return transfer(buff1, len1, NULL, 0, rxbuff, rxlen); + } + uint16_t transfer(const uint8_t *buff1, uint16_t len1, + const uint8_t *buff2, uint16_t len2, + uint8_t *rxbuff, uint16_t rxlen) + { + return transfer(buff1, len1, buff2, len2, NULL, 0, rxbuff, rxlen); + } + + uint16_t getBridgeVersion() + { + return bridgeVersion; + } + + static const uint16_t TRANSFER_TIMEOUT = 0xFFFF; + + private: + uint8_t index; + int timedRead(unsigned int timeout); + void dropAll(); + uint16_t bridgeVersion; + + private: + void crcUpdate(uint8_t c); + void crcReset(); + void crcWrite(); + bool crcCheck(uint16_t _CRC); + uint16_t CRC; + + private: + static const char CTRL_C = 3; + Stream &stream; + bool started; + uint8_t max_retries; +}; + +// This subclass uses a serial port Stream +class SerialBridgeClass : public BridgeClass { + public: + SerialBridgeClass(HardwareSerial &_serial) + : BridgeClass(_serial), serial(_serial) { + // Empty + } + + void begin(unsigned long baudrate = BRIDGE_BAUDRATE) { + serial.begin(baudrate); + BridgeClass::begin(); + } + + private: + HardwareSerial &serial; +}; + +extern SerialBridgeClass Bridge; + +// Some microcrontrollers don't start the bootloader after a reset. +// This function is intended to let the microcontroller erase its +// flash after checking a specific signal coming from the external +// device without the need to press the erase button on the board. +// The purpose is to enable a software update that does not require +// a manual interaction with the board. +extern void checkForRemoteSketchUpdate(uint8_t pin = 7); + +#endif /* BRIDGE_H_ */ + +#include +#include diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeClient.cpp b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeClient.cpp new file mode 100644 index 000000000..a342abcf2 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeClient.cpp @@ -0,0 +1,207 @@ +/* + Copyright (c) 2013 Arduino LLC. 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 + +BridgeClient::BridgeClient(uint8_t _h, BridgeClass &_b) : + bridge(_b), handle(_h), opened(true), buffered(0) { +} + +BridgeClient::BridgeClient(BridgeClass &_b) : + bridge(_b), handle(0), opened(false), buffered(0) { +} + +BridgeClient::~BridgeClient() { +} + +BridgeClient& BridgeClient::operator=(const BridgeClient &_x) { + opened = _x.opened; + handle = _x.handle; + return *this; +} + +void BridgeClient::stop() { + if (opened) { + uint8_t cmd[] = {'j', handle}; + bridge.transfer(cmd, 2); + } + opened = false; + buffered = 0; + readPos = 0; +} + +void BridgeClient::doBuffer() { + // If there are already char in buffer exit + if (buffered > 0) + return; + + // Try to buffer up to 32 characters + readPos = 0; + uint8_t cmd[] = {'K', handle, sizeof(buffer)}; + buffered = bridge.transfer(cmd, 3, buffer, sizeof(buffer)); +} + +int BridgeClient::available() { + // Look if there is new data available + doBuffer(); + return buffered; +} + +int BridgeClient::read() { + doBuffer(); + if (buffered == 0) + return -1; // no chars available + else { + buffered--; + return buffer[readPos++]; + } +} + +int BridgeClient::read(uint8_t *buff, size_t size) { + size_t readed = 0; + do { + if (buffered == 0) { + doBuffer(); + if (buffered == 0) + return readed; + } + buff[readed++] = buffer[readPos++]; + buffered--; + } while (readed < size); + return readed; +} + +int BridgeClient::peek() { + doBuffer(); + if (buffered == 0) + return -1; // no chars available + else + return buffer[readPos]; +} + +size_t BridgeClient::write(uint8_t c) { + if (!opened) + return 0; + uint8_t cmd[] = {'l', handle, c}; + bridge.transfer(cmd, 3); + return 1; +} + +size_t BridgeClient::write(const uint8_t *buf, size_t size) { + if (!opened) + return 0; + uint8_t cmd[] = {'l', handle}; + bridge.transfer(cmd, 2, buf, size, NULL, 0); + return size; +} + +void BridgeClient::flush() { +} + +uint8_t BridgeClient::connected() { + if (!opened) + return false; + // Client is "connected" if it has unread bytes + if (available()) + return true; + + uint8_t cmd[] = {'L', handle}; + uint8_t res[1]; + bridge.transfer(cmd, 2, res, 1); + return (res[0] == 1); +} + +int BridgeClient::connect(IPAddress ip, uint16_t port) { + String address; + address.reserve(18); + address += ip[0]; + address += '.'; + address += ip[1]; + address += '.'; + address += ip[2]; + address += '.'; + address += ip[3]; + return connect(address.c_str(), port); +} + +int BridgeClient::connect(const char *host, uint16_t port) { + uint8_t tmp[] = { + 'C', + static_cast(port >> 8), + static_cast(port) + }; + uint8_t res[1]; + int l = bridge.transfer(tmp, 3, (const uint8_t *)host, strlen(host), res, 1); + if (l == 0) + return 0; + handle = res[0]; + + // wait for connection + uint8_t tmp2[] = { 'c', handle }; + uint8_t res2[1]; + while (true) { + bridge.transfer(tmp2, 2, res2, 1); + if (res2[0] == 0) + break; + delay(1); + } + opened = true; + + // check for successful connection + if (connected()) + return 1; + + stop(); + handle = 0; + return 0; +} + +int BridgeClient::connectSSL(const char *host, uint16_t port) { + if (bridge.getBridgeVersion() < 161) + return -1; + + uint8_t tmp[] = { + 'Z', + static_cast(port >> 8), + static_cast(port) + }; + uint8_t res[1]; + int l = bridge.transfer(tmp, 3, (const uint8_t *)host, strlen(host), res, 1); + if (l == 0) + return 0; + handle = res[0]; + + // wait for connection + uint8_t tmp2[] = { 'c', handle }; + uint8_t res2[1]; + while (true) { + bridge.transfer(tmp2, 2, res2, 1); + if (res2[0] == 0) + break; + delay(1); + } + opened = true; + + // check for successful connection + if (connected()) + return 1; + + stop(); + handle = 0; + return 0; +} \ No newline at end of file diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeClient.h b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeClient.h new file mode 100644 index 000000000..a55ebb712 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeClient.h @@ -0,0 +1,71 @@ +/* + Copyright (c) 2013 Arduino LLC. 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 _BRIDGE_CLIENT_H_ +#define _BRIDGE_CLIENT_H_ + +#include +#include + +class BridgeClient : public Client { + public: + // Constructor with a user provided BridgeClass instance + BridgeClient(uint8_t _h, BridgeClass &_b = Bridge); + BridgeClient(BridgeClass &_b = Bridge); + ~BridgeClient(); + + // Stream methods + // (read message) + virtual int available(); + virtual int read(); + virtual int read(uint8_t *buf, size_t size); + virtual int peek(); + // (write response) + virtual size_t write(uint8_t); + virtual size_t write(const uint8_t *buf, size_t size); + virtual void flush(); + // TODO: add optimized function for block write + + virtual operator bool () { + return opened; + } + + virtual BridgeClient& operator=(const BridgeClient &_x); + + virtual void stop(); + virtual uint8_t connected(); + + virtual int connect(IPAddress ip, uint16_t port); + virtual int connect(const char *host, uint16_t port); + int connectSSL(const char* host, uint16_t port); + + private: + BridgeClass &bridge; + uint8_t handle; + boolean opened; + + private: + void doBuffer(); + uint8_t buffered; + uint8_t readPos; + static const int BUFFER_SIZE = 64; + uint8_t buffer[BUFFER_SIZE]; + +}; + +#endif // _BRIDGE_CLIENT_H_ diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeSSLClient.cpp b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeSSLClient.cpp new file mode 100644 index 000000000..dd8d34b0a --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeSSLClient.cpp @@ -0,0 +1,36 @@ +/* + Copyright (c) 2016 Arduino LLC. 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 + +BridgeSSLClient::BridgeSSLClient(uint8_t _h, BridgeClass &_b) : + BridgeClient(_h, _b) +{ +} + +BridgeSSLClient::BridgeSSLClient(BridgeClass &_b): + BridgeClient(_b) +{ +} + +BridgeSSLClient::~BridgeSSLClient() { +} + +int BridgeSSLClient::connect(const char *host, uint16_t port) { + return BridgeClient::connectSSL(host, port); +} \ No newline at end of file diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeSSLClient.h b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeSSLClient.h new file mode 100644 index 000000000..2f09afbeb --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeSSLClient.h @@ -0,0 +1,36 @@ +/* + Copyright (c) 2016 Arduino LLC. 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 _BRIDGE_SSL_CLIENT_H_ +#define _BRIDGE_SSL_CLIENT_H_ + +#include +#include +#include + +class BridgeSSLClient : public BridgeClient { + public: + // Constructor with a user provided BridgeClass instance + BridgeSSLClient(uint8_t _h, BridgeClass &_b = Bridge); + BridgeSSLClient(BridgeClass &_b = Bridge); + ~BridgeSSLClient(); + + virtual int connect(const char* host, uint16_t port); +}; + +#endif // _BRIDGE_SSL_CLIENT_H_ diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeServer.cpp b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeServer.cpp new file mode 100644 index 000000000..a7aa9b0ae --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeServer.cpp @@ -0,0 +1,54 @@ +/* + Copyright (c) 2013 Arduino LLC. 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 + +BridgeServer::BridgeServer(uint16_t _p, BridgeClass &_b) : + bridge(_b), port(_p), listening(false), useLocalhost(false) { +} + +void BridgeServer::begin() { + uint8_t tmp[] = { + 'N', + static_cast(port >> 8), + static_cast(port) + }; + uint8_t res[1]; + String address = F("127.0.0.1"); + if (!useLocalhost) + address = F("0.0.0.0"); + bridge.transfer(tmp, 3, (const uint8_t *)address.c_str(), address.length(), res, 1); + listening = (res[0] == 1); +} + +BridgeClient BridgeServer::accept() { + uint8_t cmd[] = {'k'}; + uint8_t res[1]; + unsigned int l = bridge.transfer(cmd, 1, res, 1); + if (l == 0) + return BridgeClient(); + return BridgeClient(res[0]); +} + +size_t BridgeServer::write(uint8_t c) { + uint8_t cmd[] = { 'b', c }; + bridge.transfer(cmd, 2); + return 1; +} + diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeServer.h b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeServer.h new file mode 100644 index 000000000..676a9729b --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeServer.h @@ -0,0 +1,51 @@ +/* + Copyright (c) 2013 Arduino LLC. 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 _BRIDGE_SERVER_H_ +#define _BRIDGE_SERVER_H_ + +#include +#include + +class BridgeClient; + +class BridgeServer : public Server { + public: + // Constructor with a user provided BridgeClass instance + BridgeServer(uint16_t port = 5555, BridgeClass &_b = Bridge); + + void begin(); + BridgeClient accept(); + + virtual size_t write(uint8_t c); + + void listenOnLocalhost() { + useLocalhost = true; + } + void noListenOnLocalhost() { + useLocalhost = false; + } + + private: + BridgeClass &bridge; + uint16_t port; + bool listening; + bool useLocalhost; +}; + +#endif // _BRIDGE_SERVER_H_ diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeUdp.cpp b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeUdp.cpp new file mode 100644 index 000000000..ae630e3ab --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeUdp.cpp @@ -0,0 +1,198 @@ +/* + Copyright (c) 2015 Arduino LLC. 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 "BridgeUdp.h" + +BridgeUDP::BridgeUDP(BridgeClass &_b) : + bridge(_b), opened(false), avail(0), buffered(0), readPos(0) { +} + +/* Start BridgeUDP socket, listening at local port PORT */ +uint8_t BridgeUDP::begin(uint16_t port) { + if (opened) + return 0; + uint8_t cmd[] = {'e', (uint8_t)((port >> 8) & 0xFF), (uint8_t)(port & 0xFF)}; + uint8_t res[2]; + bridge.transfer(cmd, 3, res, 2); + if (res[1] == 1) // Error... + return 0; + handle = res[0]; + opened = true; + return 1; +} + +/* Release any resources being used by this BridgeUDP instance */ +void BridgeUDP::stop() +{ + if (!opened) + return; + uint8_t cmd[] = {'q', handle}; + bridge.transfer(cmd, 2); + opened = false; +} + +int BridgeUDP::beginPacket(const char *host, uint16_t port) +{ + if (!opened) + return 0; + uint8_t cmd[] = {'E', handle, (uint8_t)((port >> 8) & 0xFF), (uint8_t)(port & 0xFF)}; + uint8_t res[1]; + bridge.transfer(cmd, 4, (const uint8_t *)host, strlen(host), res, 1); + return res[0]; // 1=Success, 0=Error +} + +int BridgeUDP::beginBroadcastPacket(uint16_t port) +{ + if (!opened) + return 0; + uint8_t cmd[] = {'v', handle, (uint8_t)((port >> 8) & 0xFF), (uint8_t)(port & 0xFF)}; + uint8_t res[1]; + bridge.transfer(cmd, 4, res, 1); + return res[0]; // 1=Success, 0=Error +} + +int BridgeUDP::beginPacket(IPAddress ip, uint16_t port) +{ + if (!opened) + return 0; + String address; + address.reserve(18); + address += ip[0]; + address += '.'; + address += ip[1]; + address += '.'; + address += ip[2]; + address += '.'; + address += ip[3]; + return beginPacket(address.c_str(), port); +} + +int BridgeUDP::endPacket() +{ + if (!opened) + return 0; + uint8_t cmd[] = {'H', handle}; + uint8_t res[1]; + bridge.transfer(cmd, 2, res, 1); + return res[0]; // 1=Success, 0=Error +} + +size_t BridgeUDP::write(const uint8_t *buffer, size_t size) +{ + if (!opened) + return 0; + uint8_t cmd[] = {'h', handle}; + uint8_t res[1]; + bridge.transfer(cmd, 2, buffer, size, res, 1); + return res[0]; // 1=Success, 0=Error +} + +int BridgeUDP::parsePacket() +{ + if (!opened) + return 0; + buffered = 0; + readPos = 0; + uint8_t cmd[] = {'Q', handle}; + uint8_t res[3]; + bridge.transfer(cmd, 2, res, 3); + if (res[0] == 0) { + // There aren't any packets available + return 0; + } + avail = (res[1] << 8) + res[2]; + return 1; +} + +void BridgeUDP::doBuffer() { + // If there are already char in buffer exit + if (buffered > 0) + return; + if (avail == 0) + return; + + // Try to buffer up to 32 characters + readPos = 0; + uint8_t cmd[] = {'u', handle, sizeof(buffer)}; + buffered = bridge.transfer(cmd, 3, buffer, sizeof(buffer)); +} + +int BridgeUDP::read() +{ + if (!opened) + return -1; + doBuffer(); + if (buffered == 0) { + return -1; // no chars available + } + buffered--; + avail--; + return buffer[readPos++]; +} + +int BridgeUDP::read(unsigned char* buff, size_t size) +{ + if (!opened) + return -1; + size_t readed = 0; + do { + if (buffered == 0) { + doBuffer(); + if (buffered == 0) + return readed; + } + buff[readed++] = buffer[readPos++]; + buffered--; + avail--; + } while (readed < size); + return readed; +} + +int BridgeUDP::peek() +{ + if (!opened) + return -1; + doBuffer(); + if (buffered == 0) + return -1; // no chars available + return buffer[readPos]; +} + +IPAddress BridgeUDP::remoteIP() +{ + if (!opened) + return -1; + uint8_t cmd[] = {'T', handle}; + uint8_t res[7]; + bridge.transfer(cmd, 2, res, 7); + if (res[0] == 0) + return IPAddress(0,0,0,0); + return IPAddress(res[1], res[2], res[3], res[4]); +} + +uint16_t BridgeUDP::remotePort() +{ + if (!opened) + return -1; + uint8_t cmd[] = {'T', handle}; + uint8_t res[7]; + bridge.transfer(cmd, 2, res, 7); + if (res[0] == 0) + return 0; + return (res[5] << 8) + res[6]; +} diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeUdp.h b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeUdp.h new file mode 100644 index 000000000..73cec54ea --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/BridgeUdp.h @@ -0,0 +1,65 @@ +/* + Copyright (c) 2015 Arduino LLC. 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 +*/ + +#pragma once + +#include +#include "Bridge.h" + +class BridgeUDP : public UDP { + + public: + BridgeUDP(BridgeClass &_b = Bridge); + virtual uint8_t begin(uint16_t); + virtual void stop(); + + virtual int beginPacket(IPAddress ip, uint16_t port); + virtual int beginPacket(const char *host, uint16_t port); + virtual int beginBroadcastPacket(uint16_t port); + virtual int endPacket(); + virtual size_t write(uint8_t d) { return write(&d, 1); } + virtual size_t write(const uint8_t *buffer, size_t size); + + using Print::write; + + virtual int parsePacket(); + /* return number of bytes available in the current packet, + will return zero if parsePacket hasn't been called yet */ + virtual int available() { return avail; } + virtual int read(); + virtual int read(unsigned char* buffer, size_t len); + virtual int read(char* buffer, size_t len) { return read((unsigned char*)buffer, len); }; + virtual int peek(); + virtual void flush() { avail = 0; } + + virtual IPAddress remoteIP(); + virtual uint16_t remotePort(); + + private: + BridgeClass &bridge; + uint8_t handle; + boolean opened; + + private: + void doBuffer(); + uint16_t avail; + uint8_t buffered; + uint8_t readPos; + static const int BUFFER_SIZE = 64; + uint8_t buffer[BUFFER_SIZE]; +}; diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/src/Console.cpp b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/Console.cpp new file mode 100644 index 000000000..7e8323d45 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/Console.cpp @@ -0,0 +1,150 @@ +/* + Copyright (c) 2013 Arduino LLC. 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 + +// Default constructor uses global Bridge instance +ConsoleClass::ConsoleClass() : + bridge(Bridge), inBuffered(0), inReadPos(0), inBuffer(NULL), + autoFlush(true) +{ + // Empty +} + +// Constructor with a user provided BridgeClass instance +ConsoleClass::ConsoleClass(BridgeClass &_b) : + bridge(_b), inBuffered(0), inReadPos(0), inBuffer(NULL), + autoFlush(true) +{ + // Empty +} + +ConsoleClass::~ConsoleClass() { + end(); +} + +size_t ConsoleClass::write(uint8_t c) { + if (autoFlush) { + uint8_t tmp[] = { 'P', c }; + bridge.transfer(tmp, 2); + } else { + outBuffer[outBuffered++] = c; + if (outBuffered == outBufferSize) + flush(); + } + return 1; +} + +size_t ConsoleClass::write(const uint8_t *buff, size_t size) { + if (autoFlush) { + uint8_t tmp[] = { 'P' }; + bridge.transfer(tmp, 1, buff, size, NULL, 0); + } else { + size_t sent = size; + while (sent > 0) { + outBuffer[outBuffered++] = *buff++; + sent--; + if (outBuffered == outBufferSize) + flush(); + } + } + return size; +} + +void ConsoleClass::flush() { + if (autoFlush) + return; + + bridge.transfer(outBuffer, outBuffered); + outBuffered = 1; +} + +void ConsoleClass::noBuffer() { + if (autoFlush) + return; + delete[] outBuffer; + autoFlush = true; +} + +void ConsoleClass::buffer(uint8_t size) { + noBuffer(); + if (size == 0) + return; + outBuffer = new uint8_t[size + 1]; + outBuffer[0] = 'P'; // WRITE tag + outBufferSize = size + 1; + outBuffered = 1; + autoFlush = false; +} + +bool ConsoleClass::connected() { + uint8_t tmp = 'a'; + bridge.transfer(&tmp, 1, &tmp, 1); + return tmp == 1; +} + +int ConsoleClass::available() { + // Look if there is new data available + doBuffer(); + return inBuffered; +} + +int ConsoleClass::read() { + doBuffer(); + if (inBuffered == 0) + return -1; // no chars available + else { + inBuffered--; + return inBuffer[inReadPos++]; + } +} + +int ConsoleClass::peek() { + doBuffer(); + if (inBuffered == 0) + return -1; // no chars available + else + return inBuffer[inReadPos]; +} + +void ConsoleClass::doBuffer() { + // If there are already char in buffer exit + if (inBuffered > 0) + return; + + // Try to buffer up to 32 characters + inReadPos = 0; + uint8_t tmp[] = { 'p', BUFFER_SIZE }; + inBuffered = bridge.transfer(tmp, 2, inBuffer, BUFFER_SIZE); +} + +void ConsoleClass::begin() { + bridge.begin(); + end(); + inBuffer = new uint8_t[BUFFER_SIZE]; +} + +void ConsoleClass::end() { + noBuffer(); + if (inBuffer) { + delete[] inBuffer; + inBuffer = NULL; + } +} + +ConsoleClass Console; diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/src/Console.h b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/Console.h new file mode 100644 index 000000000..ca05b08cf --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/Console.h @@ -0,0 +1,71 @@ +/* + Copyright (c) 2013 Arduino LLC. 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 CONSOLE_H_ +#define CONSOLE_H_ + +#include + +class ConsoleClass : public Stream { + public: + // Default constructor uses global Bridge instance + ConsoleClass(); + // Constructor with a user provided BridgeClass instance + ConsoleClass(BridgeClass &_b); + ~ConsoleClass(); + + void begin(); + void end(); + + void buffer(uint8_t size); + void noBuffer(); + + bool connected(); + + // Stream methods + // (read from console socket) + int available(); + int read(); + int peek(); + // (write to console socket) + size_t write(uint8_t); + size_t write(const uint8_t *buffer, size_t size); + void flush(); + + operator bool () { + return connected(); + } + + private: + BridgeClass &bridge; + + void doBuffer(); + uint8_t inBuffered; + uint8_t inReadPos; + static const int BUFFER_SIZE = 32; + uint8_t *inBuffer; + + bool autoFlush; + uint8_t outBuffered; + uint8_t outBufferSize; + uint8_t *outBuffer; +}; + +extern ConsoleClass Console; + +#endif diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/src/FileIO.cpp b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/FileIO.cpp new file mode 100644 index 000000000..e24a56796 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/FileIO.cpp @@ -0,0 +1,283 @@ +/* + Copyright (c) 2013 Arduino LLC. 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 + +namespace BridgeLib { + +File::File(BridgeClass &b) : bridge(b), mode(255) { + // Empty +} + +File::File(const char *_filename, uint8_t _mode, BridgeClass &b) : bridge(b), mode(_mode) { + filename = _filename; + uint8_t modes[] = {'r', 'w', 'a'}; + uint8_t cmd[] = {'F', modes[mode]}; + uint8_t res[2]; + dirPosition = 1; + bridge.transfer(cmd, 2, (uint8_t*)filename.c_str(), filename.length(), res, 2); + if (res[0] != 0) { // res[0] contains error code + mode = 255; // In case of error keep the file closed + return; + } + handle = res[1]; + buffered = 0; +} + +File::operator bool() { + return (mode != 255); +} + +File::~File() { + close(); +} + +size_t File::write(uint8_t c) { + return write(&c, 1); +} + +size_t File::write(const uint8_t *buf, size_t size) { + if (mode == 255) + return -1; + uint8_t cmd[] = {'g', handle}; + uint8_t res[1]; + bridge.transfer(cmd, 2, buf, size, res, 1); + if (res[0] != 0) // res[0] contains error code + return -res[0]; + return size; +} + +int File::read() { + doBuffer(); + if (buffered == 0) + return -1; // no chars available + else { + buffered--; + return buffer[readPos++]; + } +} + +int File::peek() { + doBuffer(); + if (buffered == 0) + return -1; // no chars available + else + return buffer[readPos]; +} + +boolean File::seek(uint32_t position) { + uint8_t cmd[] = { + 's', + handle, + static_cast(position >> 24), + static_cast(position >> 16), + static_cast(position >> 8), + static_cast(position) + }; + uint8_t res[1]; + bridge.transfer(cmd, 6, res, 1); + if (res[0] == 0) { + // If seek succeed then flush buffers + buffered = 0; + return true; + } + return false; +} + +uint32_t File::position() { + uint8_t cmd[] = {'S', handle}; + uint8_t res[5]; + bridge.transfer(cmd, 2, res, 5); + //err = res[0]; // res[0] contains error code + uint32_t pos; + pos = static_cast(res[1]) << 24; + pos += static_cast(res[2]) << 16; + pos += static_cast(res[3]) << 8; + pos += static_cast(res[4]); + return pos - buffered; +} + +void File::doBuffer() { + // If there are already char in buffer exit + if (buffered > 0) + return; + + // Try to buffer up to BUFFER_SIZE characters + readPos = 0; + uint8_t cmd[] = {'G', handle, BUFFER_SIZE - 1}; + uint16_t readed = bridge.transfer(cmd, 3, buffer, BUFFER_SIZE); + //err = buff[0]; // First byte is error code + if (readed == BridgeClass::TRANSFER_TIMEOUT || readed == 0) { + // transfer failed to retrieve any data + buffered = 0; + } else { + // transfer retrieved at least one byte of data so skip the error code character + readPos++; + buffered = readed - 1; + } +} + +int File::available() { + // Look if there is new data available + doBuffer(); + return buffered; +} + +void File::flush() { +} + +int File::read(void *buff, uint16_t nbyte) { + uint16_t n = 0; + uint8_t *p = reinterpret_cast(buff); + while (n < nbyte) { + if (buffered == 0) { + doBuffer(); + if (buffered == 0) + break; + } + *p++ = buffer[readPos++]; + buffered--; + n++; + } + return n; +} + +uint32_t File::size() { + if (bridge.getBridgeVersion() < 101) + return 0; + uint8_t cmd[] = {'t', handle}; + uint8_t buff[5]; + bridge.transfer(cmd, 2, buff, 5); + //err = res[0]; // First byte is error code + uint32_t res; + res = ((uint32_t)buff[1]) << 24; + res |= ((uint32_t)buff[2]) << 16; + res |= ((uint32_t)buff[3]) << 8; + res |= ((uint32_t)buff[4]); + return res; +} + +void File::close() { + if (mode == 255) + return; + uint8_t cmd[] = {'f', handle}; + uint8_t ret[1]; + bridge.transfer(cmd, 2, ret, 1); + mode = 255; +} + +const char *File::name() { + return filename.c_str(); +} + + +boolean File::isDirectory() { + uint8_t res[1]; + uint8_t cmd[] = {'i'}; + if (mode != 255) + return 0; + + bridge.transfer(cmd, 1, (uint8_t *)filename.c_str(), filename.length(), res, 1); + return res[0]; +} + + +File File::openNextFile(uint8_t mode) { + Process awk; + char tmp; + String command; + String filepath; + if (dirPosition == 0xFFFF) return File(); + + command = "ls "; + command += filename; + command += " | awk 'NR=="; + command += dirPosition; + command += "'"; + + awk.runShellCommand(command); + + while (awk.running()); + + command = ""; + + while (awk.available()) { + tmp = awk.read(); + if (tmp != '\n') command += tmp; + } + if (command.length() == 0) + return File(); + dirPosition++; + filepath = filename + "/" + command; + return File(filepath.c_str(), mode); + +} + +void File::rewindDirectory(void) { + dirPosition = 1; +} + + + + + + +boolean FileSystemClass::begin() { + return true; +} + +File FileSystemClass::open(const char *filename, uint8_t mode) { + return File(filename, mode); +} + +boolean FileSystemClass::exists(const char *filepath) { + Process ls; + ls.begin("ls"); + ls.addParameter(filepath); + int res = ls.run(); + return (res == 0); +} + +boolean FileSystemClass::mkdir(const char *filepath) { + Process mk; + mk.begin("mkdir"); + mk.addParameter("-p"); + mk.addParameter(filepath); + int res = mk.run(); + return (res == 0); +} + +boolean FileSystemClass::remove(const char *filepath) { + Process rm; + rm.begin("rm"); + rm.addParameter(filepath); + int res = rm.run(); + return (res == 0); +} + +boolean FileSystemClass::rmdir(const char *filepath) { + Process rm; + rm.begin("rmdir"); + rm.addParameter(filepath); + int res = rm.run(); + return (res == 0); +} + +FileSystemClass FileSystem; + +} diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/src/FileIO.h b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/FileIO.h new file mode 100644 index 000000000..c5a8e9eac --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/FileIO.h @@ -0,0 +1,120 @@ +/* + Copyright (c) 2013 Arduino LLC. 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 __FILEIO_H__ +#define __FILEIO_H__ + +#include + +#define FILE_READ 0 +#define FILE_WRITE 1 +#define FILE_APPEND 2 + +namespace BridgeLib { + +class File : public Stream { + + public: + File(BridgeClass &b = Bridge); + File(const char *_filename, uint8_t _mode, BridgeClass &b = Bridge); + ~File(); + + virtual size_t write(uint8_t); + virtual size_t write(const uint8_t *buf, size_t size); + virtual int read(); + virtual int peek(); + virtual int available(); + virtual void flush(); + int read(void *buf, uint16_t nbyte); + boolean seek(uint32_t pos); + uint32_t position(); + uint32_t size(); + void close(); + operator bool(); + const char * name(); + boolean isDirectory(); + File openNextFile(uint8_t mode = FILE_READ); + void rewindDirectory(void); + + //using Print::write; + + private: + void doBuffer(); + uint8_t buffered; + uint8_t readPos; + uint16_t dirPosition; + static const int BUFFER_SIZE = 64; + uint8_t buffer[BUFFER_SIZE]; + + + private: + BridgeClass &bridge; + String filename; + uint8_t mode; + uint8_t handle; + +}; + +class FileSystemClass { + public: + FileSystemClass() : bridge(Bridge) { } + FileSystemClass(BridgeClass &_b) : bridge(_b) { } + + boolean begin(); + + // Open the specified file/directory with the supplied mode (e.g. read or + // write, etc). Returns a File object for interacting with the file. + // Note that currently only one file can be open at a time. + File open(const char *filename, uint8_t mode = FILE_READ); + + // Methods to determine if the requested file path exists. + boolean exists(const char *filepath); + + // Create the requested directory hierarchy--if intermediate directories + // do not exist they will be created. + boolean mkdir(const char *filepath); + + // Delete the file. + boolean remove(const char *filepath); + + boolean rmdir(const char *filepath); + + private: + friend class File; + + BridgeClass &bridge; +}; + +extern FileSystemClass FileSystem; + +}; + +// We enclose File and FileSystem classes in namespace BridgeLib to avoid +// conflicts with legacy SD library. + +// This ensure compatibility with older sketches that uses only Bridge lib +// (the user can still use File instead of BridgeFile) +using namespace BridgeLib; + +// This allows sketches to use BridgeLib::File together with SD library +// (you must use BridgeFile instead of File when needed to disambiguate) +typedef BridgeLib::File BridgeFile; +typedef BridgeLib::FileSystemClass BridgeFileSystemClass; +#define BridgeFileSystem BridgeLib::FileSystem + +#endif diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/src/HttpClient.cpp b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/HttpClient.cpp new file mode 100644 index 000000000..ee1629cc3 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/HttpClient.cpp @@ -0,0 +1,204 @@ +/* + Copyright (c) 2013-2014 Arduino LLC. 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 "HttpClient.h" + +HttpClient::HttpClient() : + insecure(false) { + // Empty +} + +unsigned int HttpClient::get(String &url) { + begin("curl"); + if (insecure) { + addParameter("-k"); + } + addHeader(); + addParameter(url); + return run(); +} + +unsigned int HttpClient::get(const char *url) { + begin("curl"); + if (insecure) { + addParameter("-k"); + } + addHeader(); + addParameter(url); + return run(); +} + +void HttpClient::getAsynchronously(String &url) { + begin("curl"); + if (insecure) { + addParameter("-k"); + } + addHeader(); + addParameter(url); + runAsynchronously(); +} + +void HttpClient::getAsynchronously(const char *url) { + begin("curl"); + if (insecure) { + addParameter("-k"); + } + addHeader(); + addParameter(url); + runAsynchronously(); +} + +unsigned int HttpClient::post(String &url, String &data) { + return post(url.c_str(), data.c_str()); +} + +unsigned int HttpClient::post(const char *url, const char *data) { + begin("curl"); + if (insecure) { + addParameter("-k"); + } + addParameter("--request"); + addParameter("POST"); + addParameter("--data"); + addParameter(data); + addHeader(); + addParameter(url); + return run(); +} + +void HttpClient::postAsynchronously(String &url, String &data) { + postAsynchronously(url.c_str(), data.c_str()); +} + +void HttpClient::postAsynchronously(const char *url, const char *data) { + begin("curl"); + if (insecure) { + addParameter("-k"); + } + addParameter("--request"); + addParameter("POST"); + addParameter("--data"); + addParameter(data); + addHeader(); + addParameter(url); + runAsynchronously(); +} + +unsigned int HttpClient::patch(String &url, String &data) { + return patch(url.c_str(), data.c_str()); +} + +unsigned int HttpClient::patch(const char *url, const char *data) { + begin("curl"); + if (insecure) { + addParameter("-k"); + } + addParameter("--request"); + addParameter("PATCH"); + addParameter("--data"); + addParameter(data); + addHeader(); + addParameter(url); + return run(); +} + +void HttpClient::patchAsynchronously(String &url, String &data) { + patchAsynchronously(url.c_str(), data.c_str()); +} + +void HttpClient::patchAsynchronously(const char *url, const char *data) { + begin("curl"); + if (insecure) { + addParameter("-k"); + } + addParameter("--request"); + addParameter("PATCH"); + addParameter("--data"); + addParameter(data); + addHeader(); + addParameter(url); + runAsynchronously(); +} + +unsigned int HttpClient::put(String &url, String &data) { + return put(url.c_str(), data.c_str()); +} + +unsigned int HttpClient::put(const char *url, const char *data) { + begin("curl"); + if (insecure) { + addParameter("-k"); + } + addParameter("--request"); + addParameter("PUT"); + addParameter("--data"); + addParameter(data); + addHeader(); + addParameter(url); + return run(); +} + +void HttpClient::putAsynchronously(String &url, String &data) { + putAsynchronously(url.c_str(), data.c_str()); +} + +void HttpClient::putAsynchronously(const char *url, const char *data) { + begin("curl"); + if (insecure) { + addParameter("-k"); + } + addParameter("--request"); + addParameter("PUT"); + addParameter("--data"); + addParameter(data); + addHeader(); + addParameter(url); + runAsynchronously(); +} + +boolean HttpClient::ready() { + return !running(); +} + +unsigned int HttpClient::getResult() { + return exitValue(); +} + +void HttpClient::noCheckSSL() { + insecure = true; +} + +void HttpClient::checkSSL() { + insecure = false; +} + +void HttpClient::setHeader(String &header) { + this->header = header; +} + +void HttpClient::setHeader(const char * header) { + this->header = String(header); +} + +void HttpClient::addHeader() { + if (header.length() > 0) { + addParameter("--header"); + addParameter(header); + } +} + diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/src/HttpClient.h b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/HttpClient.h new file mode 100644 index 000000000..a6e3c77aa --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/HttpClient.h @@ -0,0 +1,59 @@ +/* + Copyright (c) 2013-2014 Arduino LLC. 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 HTTPCLIENT_H_ +#define HTTPCLIENT_H_ + +#include + +class HttpClient : public Process { + public: + HttpClient(); + + unsigned int get(String &url); + unsigned int get(const char * url); + void getAsynchronously(String &url); + void getAsynchronously(const char * url); + unsigned int post(String &url, String &data); + unsigned int post(const char * url, const char * data); + void postAsynchronously(String &url, String &data); + void postAsynchronously(const char * url, const char * data); + unsigned int patch(String &url, String &data); + unsigned int patch(const char * url, const char * data); + void patchAsynchronously(String &url, String &data); + void patchAsynchronously(const char * url, const char * data); + unsigned int put(String &url, String &data); + unsigned int put(const char * url, const char * data); + void putAsynchronously(String &url, String &data); + void putAsynchronously(const char * url, const char * data); + void setHeader(String &header); + void setHeader(const char * header); + boolean ready(); + unsigned int getResult(); + void noCheckSSL(); + void checkSSL(); + + private: + boolean insecure; + + private: + void addHeader(); + String header; +}; + +#endif /* HTTPCLIENT_H_ */ diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/src/Mailbox.cpp b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/Mailbox.cpp new file mode 100644 index 000000000..0c571f73a --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/Mailbox.cpp @@ -0,0 +1,56 @@ +/* + Copyright (c) 2013 Arduino LLC. 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 + +unsigned int MailboxClass::readMessage(uint8_t *buff, unsigned int size) { + uint8_t tmp[] = { 'm' }; + return bridge.transfer(tmp, 1, buff, size); +} + +void MailboxClass::readMessage(String &str, unsigned int maxLength) { + uint8_t tmp[] = { 'm' }; + // XXX: Is there a better way to create the string? + uint8_t buff[maxLength + 1]; + int l = bridge.transfer(tmp, 1, buff, maxLength); + buff[l] = 0; + str = (const char *)buff; +} + +void MailboxClass::writeMessage(const uint8_t *buff, unsigned int size) { + uint8_t cmd[] = {'M'}; + bridge.transfer(cmd, 1, buff, size, NULL, 0); +} + +void MailboxClass::writeMessage(const String& str) { + writeMessage((uint8_t*) str.c_str(), str.length()); +} + +void MailboxClass::writeJSON(const String& str) { + uint8_t cmd[] = {'J'}; + bridge.transfer(cmd, 1, (uint8_t*) str.c_str(), str.length(), NULL, 0); +} + +unsigned int MailboxClass::messageAvailable() { + uint8_t tmp[] = {'n'}; + uint8_t res[2]; + bridge.transfer(tmp, 1, res, 2); + return (res[0] << 8) + res[1]; +} + +MailboxClass Mailbox(Bridge); diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/src/Mailbox.h b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/Mailbox.h new file mode 100644 index 000000000..b2e383308 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/Mailbox.h @@ -0,0 +1,53 @@ +/* + Copyright (c) 2013 Arduino LLC. 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 _MAILBOX_CLASS_H_INCLUDED_ +#define _MAILBOX_CLASS_H_INCLUDED_ + +#include + +class MailboxClass { + public: + MailboxClass(BridgeClass &b = Bridge) : bridge(b) { } + + void begin() { } + void end() { } + + // Receive a message and store it inside a buffer + unsigned int readMessage(uint8_t *buffer, unsigned int size); + // Receive a message and store it inside a String + void readMessage(String &str, unsigned int maxLength = 128); + + // Send a message + void writeMessage(const uint8_t *buffer, unsigned int size); + // Send a message + void writeMessage(const String& str); + // Send a JSON message + void writeJSON(const String& str); + + // Return the size of the next available message, 0 if there are + // no messages in queue. + unsigned int messageAvailable(); + + private: + BridgeClass &bridge; +}; + +extern MailboxClass Mailbox; + +#endif // _MAILBOX_CLASS_H_INCLUDED_ diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/src/Process.cpp b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/Process.cpp new file mode 100644 index 000000000..987f0b8ac --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/Process.cpp @@ -0,0 +1,142 @@ +/* + Copyright (c) 2013 Arduino LLC. 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 + +Process::~Process() { + close(); +} + +size_t Process::write(uint8_t c) { + uint8_t cmd[] = {'I', handle, c}; + bridge.transfer(cmd, 3); + return 1; +} + +void Process::flush() { +} + +int Process::available() { + // Look if there is new data available + doBuffer(); + return buffered; +} + +int Process::read() { + doBuffer(); + if (buffered == 0) + return -1; // no chars available + else { + buffered--; + return buffer[readPos++]; + } +} + +int Process::peek() { + doBuffer(); + if (buffered == 0) + return -1; // no chars available + else + return buffer[readPos]; +} + +void Process::doBuffer() { + // If there are already char in buffer exit + if (buffered > 0) + return; + + // Try to buffer up to 32 characters + readPos = 0; + uint8_t cmd[] = {'O', handle, sizeof(buffer)}; + buffered = bridge.transfer(cmd, 3, buffer, sizeof(buffer)); +} + +void Process::begin(const String &command) { + close(); + cmdline = new String(command); +} + +void Process::addParameter(const String ¶m) { + *cmdline += "\xFE"; + *cmdline += param; +} + +void Process::runAsynchronously() { + uint8_t cmd[] = {'R'}; + uint8_t res[2]; + bridge.transfer(cmd, 1, (uint8_t*)cmdline->c_str(), cmdline->length(), res, 2); + handle = res[1]; + + delete cmdline; + cmdline = NULL; + + if (res[0] == 0) // res[0] contains error code + started = true; +} + +boolean Process::running() { + uint8_t cmd[] = {'r', handle}; + uint8_t res[1]; + bridge.transfer(cmd, 2, res, 1); + return (res[0] == 1); +} + +unsigned int Process::exitValue() { + uint8_t cmd[] = {'W', handle}; + uint8_t res[2]; + bridge.transfer(cmd, 2, res, 2); + return (res[0] << 8) + res[1]; +} + +unsigned int Process::run() { + runAsynchronously(); + while (running()) + delay(100); + return exitValue(); +} + +void Process::close() { + if (started) { + uint8_t cmd[] = {'w', handle}; + bridge.transfer(cmd, 2); + } + started = false; +} + +unsigned int Process::runShellCommand(const String &command) { + runShellCommandAsynchronously(command); + while (running()) + delay(100); + return exitValue(); +} + +void Process::runShellCommandAsynchronously(const String &command) { + begin("/bin/ash"); + addParameter("-c"); + addParameter(command); + runAsynchronously(); +} + +// This method is currently unused +//static unsigned int __commandOutputAvailable(uint8_t handle) { +// uint8_t cmd[] = {'o', handle}; +// uint8_t res[1]; +// Bridge.transfer(cmd, 2, res, 1); +// return res[0]; +//} + diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/src/Process.h b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/Process.h new file mode 100644 index 000000000..7002764a0 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/Process.h @@ -0,0 +1,71 @@ +/* + Copyright (c) 2013 Arduino LLC. 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 PROCESS_H_ +#define PROCESS_H_ + +#include + +class Process : public Stream { + public: + // Constructor with a user provided BridgeClass instance + Process(BridgeClass &_b = Bridge) : + bridge(_b), started(false), buffered(0), readPos(0) { } + ~Process(); + + void begin(const String &command); + void addParameter(const String ¶m); + unsigned int run(); + void runAsynchronously(); + boolean running(); + unsigned int exitValue(); + void close(); + + unsigned int runShellCommand(const String &command); + void runShellCommandAsynchronously(const String &command); + + operator bool () { + return started; + } + + // Stream methods + // (read from process stdout) + int available(); + int read(); + int peek(); + // (write to process stdin) + size_t write(uint8_t); + void flush(); + // TODO: add optimized function for block write + + private: + BridgeClass &bridge; + uint8_t handle; + String *cmdline; + boolean started; + + private: + void doBuffer(); + uint8_t buffered; + uint8_t readPos; + static const int BUFFER_SIZE = 64; + uint8_t buffer[BUFFER_SIZE]; + +}; + +#endif diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/src/YunClient.h b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/YunClient.h new file mode 100644 index 000000000..faff247c9 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/YunClient.h @@ -0,0 +1,27 @@ +/* + Copyright (c) 2014 Arduino LLC. 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 _YUN_CLIENT_H_ +#define _YUN_CLIENT_H_ + +#include + +#warning "The use of YunClient is deprecated. Use BridgeClient instead!" +typedef BridgeClient YunClient; + +#endif // _YUN_CLIENT_H_ diff --git a/app/testdata/libraries/Bridge_1.6.3/Bridge/src/YunServer.h b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/YunServer.h new file mode 100644 index 000000000..95d05cd71 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.6.3/Bridge/src/YunServer.h @@ -0,0 +1,27 @@ +/* + Copyright (c) 2014 Arduino LLC. 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 _YUN_SERVER_H_ +#define _YUN_SERVER_H_ + +#include + +#warning "The use of YunServer is deprecated. Use BridgeServer instead!" +typedef BridgeServer YunServer; + +#endif // _YUN_SERVER_H_ diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/README.adoc b/app/testdata/libraries/Bridge_1.7.0/Bridge/README.adoc new file mode 100644 index 000000000..c660f86ee --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/README.adoc @@ -0,0 +1,24 @@ += Bridge Library for Arduino = + +The Bridge library simplifies communication between the ATmega32U4 and the AR9331. + +For more information about this library please visit us at +http://www.arduino.cc/en/Reference/YunBridgeLibrary + +== License == + +Copyright (c) 2014 Arduino LLC. 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 diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/Bridge/Bridge.ino b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/Bridge/Bridge.ino new file mode 100644 index 000000000..35c3aac5a --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/Bridge/Bridge.ino @@ -0,0 +1,183 @@ +/* + Arduino Yún Bridge example + + This example for the YunShield/Yún shows how + to use the Bridge library to access the digital and + analog pins on the board through REST calls. + It demonstrates how you can create your own API when + using REST style calls through the browser. + + Possible commands created in this shetch: + + "/arduino/digital/13" -> digitalRead(13) + "/arduino/digital/13/1" -> digitalWrite(13, HIGH) + "/arduino/analog/2/123" -> analogWrite(2, 123) + "/arduino/analog/2" -> analogRead(2) + "/arduino/mode/13/input" -> pinMode(13, INPUT) + "/arduino/mode/13/output" -> pinMode(13, OUTPUT) + + This example code is part of the public domain + + http://www.arduino.cc/en/Tutorial/Bridge + +*/ + +#include +#include +#include + +// Listen to the default port 5555, the Yún webserver +// will forward there all the HTTP requests you send +BridgeServer server; + +void setup() { + // Bridge startup + pinMode(13, OUTPUT); + digitalWrite(13, LOW); + Bridge.begin(); + digitalWrite(13, HIGH); + + // Listen for incoming connection only from localhost + // (no one from the external network could connect) + server.listenOnLocalhost(); + server.begin(); +} + +void loop() { + // Get clients coming from server + BridgeClient client = server.accept(); + + // There is a new client? + if (client) { + // Process request + process(client); + + // Close connection and free resources. + client.stop(); + } + + delay(50); // Poll every 50ms +} + +void process(BridgeClient client) { + // read the command + String command = client.readStringUntil('/'); + + // is "digital" command? + if (command == "digital") { + digitalCommand(client); + } + + // is "analog" command? + if (command == "analog") { + analogCommand(client); + } + + // is "mode" command? + if (command == "mode") { + modeCommand(client); + } +} + +void digitalCommand(BridgeClient client) { + int pin, value; + + // Read pin number + pin = client.parseInt(); + + // If the next character is a '/' it means we have an URL + // with a value like: "/digital/13/1" + if (client.read() == '/') { + value = client.parseInt(); + digitalWrite(pin, value); + } else { + value = digitalRead(pin); + } + + // Send feedback to client + client.print(F("Pin D")); + client.print(pin); + client.print(F(" set to ")); + client.println(value); + + // Update datastore key with the current pin value + String key = "D"; + key += pin; + Bridge.put(key, String(value)); +} + +void analogCommand(BridgeClient client) { + int pin, value; + + // Read pin number + pin = client.parseInt(); + + // If the next character is a '/' it means we have an URL + // with a value like: "/analog/5/120" + if (client.read() == '/') { + // Read value and execute command + value = client.parseInt(); + analogWrite(pin, value); + + // Send feedback to client + client.print(F("Pin D")); + client.print(pin); + client.print(F(" set to analog ")); + client.println(value); + + // Update datastore key with the current pin value + String key = "D"; + key += pin; + Bridge.put(key, String(value)); + } else { + // Read analog pin + value = analogRead(pin); + + // Send feedback to client + client.print(F("Pin A")); + client.print(pin); + client.print(F(" reads analog ")); + client.println(value); + + // Update datastore key with the current pin value + String key = "A"; + key += pin; + Bridge.put(key, String(value)); + } +} + +void modeCommand(BridgeClient client) { + int pin; + + // Read pin number + pin = client.parseInt(); + + // If the next character is not a '/' we have a malformed URL + if (client.read() != '/') { + client.println(F("error")); + return; + } + + String mode = client.readStringUntil('\r'); + + if (mode == "input") { + pinMode(pin, INPUT); + // Send feedback to client + client.print(F("Pin D")); + client.print(pin); + client.print(F(" configured as INPUT!")); + return; + } + + if (mode == "output") { + pinMode(pin, OUTPUT); + // Send feedback to client + client.print(F("Pin D")); + client.print(pin); + client.print(F(" configured as OUTPUT!")); + return; + } + + client.print(F("error: invalid mode ")); + client.print(mode); +} diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/ConsoleAsciiTable/ConsoleAsciiTable.ino b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/ConsoleAsciiTable/ConsoleAsciiTable.ino new file mode 100644 index 000000000..e8b07d7aa --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/ConsoleAsciiTable/ConsoleAsciiTable.ino @@ -0,0 +1,95 @@ +/* + Console ASCII table for YunShield/Yún + Prints out byte values in all possible formats: + * as raw binary values + * as ASCII-encoded decimal, hex, octal, and binary values + + For more on ASCII, see http://www.asciitable.com and http://en.wikipedia.org/wiki/ASCII + + The circuit: + - YunShield/Yún + + created 2006 + by Nicholas Zambetti + http://www.zambetti.com + modified 9 Apr 2012 + by Tom Igoe + modified 22 May 2013 + by Cristian Maglie + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/ConsoleAsciiTable + + */ + +#include + +void setup() { + //Initialize Console and wait for port to open: + Bridge.begin(); + Console.begin(); + + // Uncomment the following line to enable buffering: + // - better transmission speed and efficiency + // - needs to call Console.flush() to ensure that all + // transmitted data is sent + + //Console.buffer(64); + + while (!Console) { + ; // wait for Console port to connect. + } + + // prints title with ending line break + Console.println("ASCII Table ~ Character Map"); +} + +// first visible ASCIIcharacter '!' is number 33: +int thisByte = 33; +// you can also write ASCII characters in single quotes. +// for example. '!' is the same as 33, so you could also use this: +//int thisByte = '!'; + +void loop() { + // prints value unaltered, i.e. the raw binary version of the + // byte. The Console monitor interprets all bytes as + // ASCII, so 33, the first number, will show up as '!' + Console.write(thisByte); + + Console.print(", dec: "); + // prints value as string as an ASCII-encoded decimal (base 10). + // Decimal is the default format for Console.print() and Console.println(), + // so no modifier is needed: + Console.print(thisByte); + // But you can declare the modifier for decimal if you want to. + //this also works if you uncomment it: + + // Console.print(thisByte, DEC); + + Console.print(", hex: "); + // prints value as string in hexadecimal (base 16): + Console.print(thisByte, HEX); + + Console.print(", oct: "); + // prints value as string in octal (base 8); + Console.print(thisByte, OCT); + + Console.print(", bin: "); + // prints value as string in binary (base 2) + // also prints ending line break: + Console.println(thisByte, BIN); + + // if printed last visible character '~' or 126, stop: + if (thisByte == 126) { // you could also use if (thisByte == '~') { + // ensure the latest bit of data is sent + Console.flush(); + + // This loop loops forever and does nothing + while (true) { + continue; + } + } + // go on to the next character + thisByte++; +} diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/ConsolePixel/ConsolePixel.ino b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/ConsolePixel/ConsolePixel.ino new file mode 100644 index 000000000..6479b135b --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/ConsolePixel/ConsolePixel.ino @@ -0,0 +1,63 @@ +/* + Console Pixel + + An example of using YunShield/Yún board to receive data from the + Console on the Yún. In this case, the board turns on an LED when + it receives the character 'H', and turns off the LED when it + receives the character 'L'. + + To see the Console, pick your Yún's name and IP address in the Port menu + then open the Port Monitor. You can also see it by opening a terminal window + and typing + ssh root@ yourYunsName.local 'telnet localhost 6571' + then pressing enter. When prompted for the password, enter it. + + + The circuit: + * LED connected from digital pin 13 to ground + + created 2006 + by David A. Mellis + modified 25 Jun 2013 + by Tom Igoe + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/ConsolePixel + + */ + +#include + +const int ledPin = 13; // the pin that the LED is attached to +char incomingByte; // a variable to read incoming Console data into + +void setup() { + Bridge.begin(); // Initialize Bridge + Console.begin(); // Initialize Console + + // Wait for the Console port to connect + while (!Console); + + Console.println("type H or L to turn pin 13 on or off"); + + // initialize the LED pin as an output: + pinMode(ledPin, OUTPUT); +} + +void loop() { + // see if there's incoming Console data: + if (Console.available() > 0) { + // read the oldest byte in the Console buffer: + incomingByte = Console.read(); + Console.println(incomingByte); + // if it's a capital H (ASCII 72), turn on the LED: + if (incomingByte == 'H') { + digitalWrite(ledPin, HIGH); + } + // if it's an L (ASCII 76) turn off the LED: + if (incomingByte == 'L') { + digitalWrite(ledPin, LOW); + } + } +} diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/ConsoleRead/ConsoleRead.ino b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/ConsoleRead/ConsoleRead.ino new file mode 100644 index 000000000..fc63fcc6d --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/ConsoleRead/ConsoleRead.ino @@ -0,0 +1,58 @@ +/* +Console Read example for YunShield/Yún + + Read data coming from bridge using the Console.read() function + and store it in a string. + + To see the Console, pick your Yún's name and IP address in the Port menu + then open the Port Monitor. You can also see it by opening a terminal window + and typing: + ssh root@ yourYunsName.local 'telnet localhost 6571' + then pressing enter. When prompted for the password, enter it. + + created 13 Jun 2013 + by Angelo Scialabba + modified 16 June 2013 + by Tom Igoe + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/ConsoleRead + + */ + +#include + +String name; + +void setup() { + // Initialize Console and wait for port to open: + Bridge.begin(); + Console.begin(); + + // Wait for Console port to connect + while (!Console); + + Console.println("Hi, what's your name?"); +} + +void loop() { + if (Console.available() > 0) { + char c = Console.read(); // read the next char received + // look for the newline character, this is the last character in the string + if (c == '\n') { + //print text with the name received + Console.print("Hi "); + Console.print(name); + Console.println("! Nice to meet you!"); + Console.println(); + // Ask again for name and clear the old name + Console.println("Hi, what's your name?"); + name = ""; // clear the name string + } else { // if the buffer is empty Cosole.read() returns -1 + name += c; // append the read char from Console to the name string + } + } else { + delay(100); + } +} diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/Datalogger/Datalogger.ino b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/Datalogger/Datalogger.ino new file mode 100644 index 000000000..cc84828a0 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/Datalogger/Datalogger.ino @@ -0,0 +1,102 @@ +/* + SD card datalogger + + This example shows how to log data from three analog sensors + to an SD card mounted on the YunShield/Yún using the Bridge library. + + The circuit: + * analog sensors on analog pins 0, 1 and 2 + * SD card attached to SD card slot of the YunShield/Yún + + Prepare your SD card creating an empty folder in the SD root + named "arduino". This will ensure that the Yún will create a link + to the SD to the "/mnt/sd" path. + + You can remove the SD card while the Linux and the + sketch are running but be careful not to remove it while + the system is writing to it. + + created 24 Nov 2010 + modified 9 Apr 2012 + by Tom Igoe + adapted to the Yún Bridge library 20 Jun 2013 + by Federico Vanzati + modified 21 Jun 2013 + by Tom Igoe + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/YunDatalogger + + */ + +#include + +void setup() { + // Initialize the Bridge and the Serial + Bridge.begin(); + Serial.begin(9600); + FileSystem.begin(); + + while (!SerialUSB); // wait for Serial port to connect. + SerialUSB.println("Filesystem datalogger\n"); +} + + +void loop() { + // make a string that start with a timestamp for assembling the data to log: + String dataString; + dataString += getTimeStamp(); + dataString += " = "; + + // read three sensors and append to the string: + for (int analogPin = 0; analogPin < 3; analogPin++) { + int sensor = analogRead(analogPin); + dataString += String(sensor); + if (analogPin < 2) { + dataString += ","; // separate the values with a comma + } + } + + // open the file. note that only one file can be open at a time, + // so you have to close this one before opening another. + // The FileSystem card is mounted at the following "/mnt/FileSystema1" + File dataFile = FileSystem.open("/mnt/sd/datalog.txt", FILE_APPEND); + + // if the file is available, write to it: + if (dataFile) { + dataFile.println(dataString); + dataFile.close(); + // print to the serial port too: + SerialUSB.println(dataString); + } + // if the file isn't open, pop up an error: + else { + SerialUSB.println("error opening datalog.txt"); + } + + delay(15000); + +} + +// This function return a string with the time stamp +String getTimeStamp() { + String result; + Process time; + // date is a command line utility to get the date and the time + // in different formats depending on the additional parameter + time.begin("date"); + time.addParameter("+%D-%T"); // parameters: D for the complete date mm/dd/yy + // T for the time hh:mm:ss + time.run(); // run the command + + // read the output of the command + while (time.available() > 0) { + char c = time.read(); + if (c != '\n') { + result += c; + } + } + + return result; +} diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/FileWriteScript/FileWriteScript.ino b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/FileWriteScript/FileWriteScript.ino new file mode 100644 index 000000000..e080bce36 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/FileWriteScript/FileWriteScript.ino @@ -0,0 +1,83 @@ +/* + Write to file using FileIO classes. + + This sketch demonstrate how to write file into the YunShield/Yún filesystem. + A shell script file is created in /tmp, and it is executed afterwards. + + created 7 June 2010 + by Cristian Maglie + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/FileWriteScript + + */ + +#include + +void setup() { + // Setup Bridge (needed every time we communicate with the Arduino Yún) + Bridge.begin(); + // Initialize the Serial + SerialUSB.begin(9600); + + while (!SerialUSB); // wait for Serial port to connect. + SerialUSB.println("File Write Script example\n\n"); + + // Setup File IO + FileSystem.begin(); + + // Upload script used to gain network statistics + uploadScript(); +} + +void loop() { + // Run stats script every 5 secs. + runScript(); + delay(5000); +} + +// this function creates a file into the linux processor that contains a shell script +// to check the network traffic of the WiFi interface +void uploadScript() { + // Write our shell script in /tmp + // Using /tmp stores the script in RAM this way we can preserve + // the limited amount of FLASH erase/write cycles + File script = FileSystem.open("/tmp/wlan-stats.sh", FILE_WRITE); + // Shell script header + script.print("#!/bin/sh\n"); + // shell commands: + // ifconfig: is a command line utility for controlling the network interfaces. + // wlan0 is the interface we want to query + // grep: search inside the output of the ifconfig command the "RX bytes" keyword + // and extract the line that contains it + script.print("ifconfig wlan0 | grep 'RX bytes'\n"); + script.close(); // close the file + + // Make the script executable + Process chmod; + chmod.begin("chmod"); // chmod: change mode + chmod.addParameter("+x"); // x stays for executable + chmod.addParameter("/tmp/wlan-stats.sh"); // path to the file to make it executable + chmod.run(); +} + + +// this function run the script and read the output data +void runScript() { + // Run the script and show results on the Serial + Process myscript; + myscript.begin("/tmp/wlan-stats.sh"); + myscript.run(); + + String output = ""; + + // read the output of the script + while (myscript.available()) { + output += (char)myscript.read(); + } + // remove the blank spaces at the beginning and the ending of the string + output.trim(); + SerialUSB.println(output); + SerialUSB.flush(); +} diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/HttpClient/HttpClient.ino b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/HttpClient/HttpClient.ino new file mode 100644 index 000000000..47a37c3f2 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/HttpClient/HttpClient.ino @@ -0,0 +1,51 @@ +/* + Yún HTTP Client + + This example for the YunShield/Yún shows how create a basic + HTTP client that connects to the internet and downloads + content. In this case, you'll connect to the Arduino + website and download a version of the logo as ASCII text. + + created by Tom igoe + May 2013 + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/HttpClient + + */ + +#include +#include + +void setup() { + // Bridge takes about two seconds to start up + // it can be helpful to use the on-board LED + // as an indicator for when it has initialized + pinMode(13, OUTPUT); + digitalWrite(13, LOW); + Bridge.begin(); + digitalWrite(13, HIGH); + + SerialUSB.begin(9600); + + while (!SerialUSB); // wait for a serial connection +} + +void loop() { + // Initialize the client library + HttpClient client; + + // Make a HTTP request: + client.get("http://www.arduino.cc/asciilogo.txt"); + + // if there are incoming bytes available + // from the server, read them and print them: + while (client.available()) { + char c = client.read(); + SerialUSB.print(c); + } + SerialUSB.flush(); + + delay(5000); +} diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/HttpClientConsole/HttpClientConsole.ino b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/HttpClientConsole/HttpClientConsole.ino new file mode 100644 index 000000000..3b07f601c --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/HttpClientConsole/HttpClientConsole.ino @@ -0,0 +1,53 @@ +/* + Yún HTTP Client Console version for Arduino Uno and Mega using Yún Shield + + This example for the YunShield/Yún shows how create a basic + HTTP client that connects to the internet and downloads + content. In this case, you'll connect to the Arduino + website and download a version of the logo as ASCII text. + + created by Tom igoe + May 2013 + modified by Marco Brianza to use Console + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/HttpClient + + */ + +#include +#include +#include + +void setup() { + // Bridge takes about two seconds to start up + // it can be helpful to use the on-board LED + // as an indicator for when it has initialized + pinMode(13, OUTPUT); + digitalWrite(13, LOW); + Bridge.begin(); + digitalWrite(13, HIGH); + + Console.begin(); + + while (!Console); // wait for a serial connection +} + +void loop() { + // Initialize the client library + HttpClient client; + + // Make a HTTP request: + client.get("http://www.arduino.cc/asciilogo.txt"); + + // if there are incoming bytes available + // from the server, read them and print them: + while (client.available()) { + char c = client.read(); + Console.print(c); + } + Console.flush(); + + delay(5000); +} diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/MailboxReadMessage/MailboxReadMessage.ino b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/MailboxReadMessage/MailboxReadMessage.ino new file mode 100644 index 000000000..11aaecd3d --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/MailboxReadMessage/MailboxReadMessage.ino @@ -0,0 +1,58 @@ +/* + Read Messages from the Mailbox + + This example for the YunShield/Yún shows how to + read the messages queue, called Mailbox, using the + Bridge library. + The messages can be sent to the queue through REST calls. + Appen the message in the URL after the keyword "/mailbox". + Example + + "/mailbox/hello" + + created 3 Feb 2014 + by Federico Vanzati & Federico Fissore + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/MailboxReadMessage + + */ + +#include + +void setup() { + pinMode(13, OUTPUT); + digitalWrite(13, LOW); + // Initialize Bridge and Mailbox + Bridge.begin(); + Mailbox.begin(); + digitalWrite(13, HIGH); + + // Initialize Serial + SerialUSB.begin(9600); + + // Wait until a Serial Monitor is connected. + while (!SerialUSB); + + SerialUSB.println("Mailbox Read Message\n"); + SerialUSB.println("The Mailbox is checked every 10 seconds. The incoming messages will be shown below.\n"); +} + +void loop() { + String message; + + // if there is a message in the Mailbox + if (Mailbox.messageAvailable()) { + // read all the messages present in the queue + while (Mailbox.messageAvailable()) { + Mailbox.readMessage(message); + SerialUSB.println(message); + } + + SerialUSB.println("Waiting 10 seconds before checking the Mailbox again"); + } + + // wait 10 seconds + delay(10000); +} diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/Process/Process.ino b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/Process/Process.ino new file mode 100644 index 000000000..7f5752c77 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/Process/Process.ino @@ -0,0 +1,71 @@ +/* + Running process using Process class. + + This sketch demonstrate how to run linux processes + using a YunShield/Yún + + created 5 Jun 2013 + by Cristian Maglie + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/Process + + */ + +#include + +void setup() { + // Initialize Bridge + Bridge.begin(); + + // Initialize Serial + SerialUSB.begin(9600); + + // Wait until a Serial Monitor is connected. + while (!SerialUSB); + + // run various example processes + runCurl(); + runCpuInfo(); +} + +void loop() { + // Do nothing here. +} + +void runCurl() { + // Launch "curl" command and get Arduino ascii art logo from the network + // curl is command line program for transferring data using different internet protocols + Process p; // Create a process and call it "p" + p.begin("curl"); // Process that launch the "curl" command + p.addParameter("http://www.arduino.cc/asciilogo.txt"); // Add the URL parameter to "curl" + p.run(); // Run the process and wait for its termination + + // Print arduino logo over the Serial + // A process output can be read with the stream methods + while (p.available() > 0) { + char c = p.read(); + SerialUSB.print(c); + } + // Ensure the last bit of data is sent. + SerialUSB.flush(); +} + +void runCpuInfo() { + // Launch "cat /proc/cpuinfo" command (shows info on Atheros CPU) + // cat is a command line utility that shows the content of a file + Process p; // Create a process and call it "p" + p.begin("cat"); // Process that launch the "cat" command + p.addParameter("/proc/cpuinfo"); // Add the cpuifo file path as parameter to cut + p.run(); // Run the process and wait for its termination + + // Print command output on the SerialUSB. + // A process output can be read with the stream methods + while (p.available() > 0) { + char c = p.read(); + SerialUSB.print(c); + } + // Ensure the last bit of data is sent. + SerialUSB.flush(); +} diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/RemoteDueBlink/RemoteDueBlink.ino b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/RemoteDueBlink/RemoteDueBlink.ino new file mode 100644 index 000000000..4b5d2713c --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/RemoteDueBlink/RemoteDueBlink.ino @@ -0,0 +1,33 @@ +/* + 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://www.arduino.cc + + This example code is in the public domain. + + modified 8 May 2014 + by Scott Fitzgerald + + modified by Marco Brianza to show the remote sketch update feature on Arduino Due using Yún Shield + */ + +#include + +// the setup function runs once when you press reset or power the board +void setup() { + checkForRemoteSketchUpdate(); + // initialize digital pin 13 as an output. + pinMode(13, OUTPUT); +} + +// the loop function runs over and over again forever +void loop() { + digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level) + delay(100); // wait for a second + digitalWrite(13, LOW); // turn the LED off by making the voltage LOW + delay(100); // wait for a second +} diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/ShellCommands/ShellCommands.ino b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/ShellCommands/ShellCommands.ino new file mode 100644 index 000000000..acd82896e --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/ShellCommands/ShellCommands.ino @@ -0,0 +1,52 @@ +/* + Running shell commands using Process class. + + This sketch demonstrate how to run linux shell commands + using a YunShield/Yún. It runs the wifiCheck script on the Linux side + of the Yún, then uses grep to get just the signal strength line. + Then it uses parseInt() to read the wifi signal strength as an integer, + and finally uses that number to fade an LED using analogWrite(). + + The circuit: + * YunShield/Yún with LED connected to pin 9 + + created 12 Jun 2013 + by Cristian Maglie + modified 25 June 2013 + by Tom Igoe + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/ShellCommands + + */ + +#include + +void setup() { + Bridge.begin(); // Initialize the Bridge + SerialUSB.begin(9600); // Initialize the Serial + + // Wait until a Serial Monitor is connected. + while (!SerialUSB); +} + +void loop() { + Process p; + // This command line runs the WifiStatus script, (/usr/bin/pretty-wifi-info.lua), then + // sends the result to the grep command to look for a line containing the word + // "Signal:" the result is passed to this sketch: + p.runShellCommand("/usr/bin/pretty-wifi-info.lua | grep Signal"); + + // do nothing until the process finishes, so you get the whole output: + while (p.running()); + + // Read command output. runShellCommand() should have passed "Signal: xx&": + while (p.available()) { + int result = p.parseInt(); // look for an integer + int signal = map(result, 0, 100, 0, 255); // map result from 0-100 range to 0-255 + analogWrite(9, signal); // set the brightness of LED on pin 9 + SerialUSB.println(result); // print the number as well + } + delay(5000); // wait 5 seconds before you do it again +} diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/TemperatureWebPanel/TemperatureWebPanel.ino b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/TemperatureWebPanel/TemperatureWebPanel.ino new file mode 100644 index 000000000..7bf25a8a0 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/TemperatureWebPanel/TemperatureWebPanel.ino @@ -0,0 +1,122 @@ +/* + Temperature web interface + + This example shows how to serve data from an analog input + via the YunShield/Yún built-in webserver using the Bridge library. + + The circuit: + * TMP36 temperature sensor on analog pin A1 + * SD card attached to SD card slot of the YunShield/Yún + + This sketch must be uploaded via wifi. REST API must be set to "open". + + Prepare your SD card with an empty folder in the SD root + named "arduino" and a subfolder of that named "www". + This will ensure that the Yún will create a link + to the SD to the "/mnt/sd" path. + + In this sketch folder is a basic webpage and a copy of zepto.js, a + minimized version of jQuery. When you upload your sketch, these files + will be placed in the /arduino/www/TemperatureWebPanel folder on your SD card. + + You can then go to http://arduino.local/sd/TemperatureWebPanel + to see the output of this sketch. + + You can remove the SD card while the Linux and the + sketch are running but be careful not to remove it while + the system is writing to it. + + created 6 July 2013 + by Tom Igoe + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/TemperatureWebPanel + + */ + +#include +#include +#include + +// Listen on default port 5555, the webserver on the Yún +// will forward there all the HTTP requests for us. +BridgeServer server; +String startString; +long hits = 0; + +void setup() { + SerialUSB.begin(9600); + + // Bridge startup + pinMode(13, OUTPUT); + digitalWrite(13, LOW); + Bridge.begin(); + digitalWrite(13, HIGH); + + // using A0 and A2 as vcc and gnd for the TMP36 sensor: + pinMode(A0, OUTPUT); + pinMode(A2, OUTPUT); + digitalWrite(A0, HIGH); + digitalWrite(A2, LOW); + + // Listen for incoming connection only from localhost + // (no one from the external network could connect) + server.listenOnLocalhost(); + server.begin(); + + // get the time that this sketch started: + Process startTime; + startTime.runShellCommand("date"); + while (startTime.available()) { + char c = startTime.read(); + startString += c; + } +} + +void loop() { + // Get clients coming from server + BridgeClient client = server.accept(); + + // There is a new client? + if (client) { + // read the command + String command = client.readString(); + command.trim(); //kill whitespace + SerialUSB.println(command); + // is "temperature" command? + if (command == "temperature") { + + // get the time from the server: + Process time; + time.runShellCommand("date"); + String timeString = ""; + while (time.available()) { + char c = time.read(); + timeString += c; + } + SerialUSB.println(timeString); + int sensorValue = analogRead(A1); + // convert the reading to millivolts: + float voltage = sensorValue * (5000.0f / 1024.0f); + // convert the millivolts to temperature celsius: + float temperature = (voltage - 500.0f) / 10.0f; + // print the temperature: + client.print("Current time on the Yún: "); + client.println(timeString); + client.print("
Current temperature: "); + client.print(temperature); + client.print(" °C"); + client.print("
This sketch has been running since "); + client.print(startString); + client.print("
Hits so far: "); + client.print(hits); + } + + // Close connection and free resources. + client.stop(); + hits++; + } + + delay(50); // Poll every 50ms +} diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/TemperatureWebPanel/www/index.html b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/TemperatureWebPanel/www/index.html new file mode 100644 index 000000000..c6b674771 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/TemperatureWebPanel/www/index.html @@ -0,0 +1,16 @@ + + + + + + + + + 0 + + + diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/TemperatureWebPanel/www/zepto.min.js b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/TemperatureWebPanel/www/zepto.min.js new file mode 100644 index 000000000..dbe4e3c3f --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/TemperatureWebPanel/www/zepto.min.js @@ -0,0 +1,2 @@ +/* Zepto v1.0-1-ga3cab6c - polyfill zepto detect event ajax form fx - zeptojs.com/license */ +(function(a){String.prototype.trim===a&&(String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g,"")}),Array.prototype.reduce===a&&(Array.prototype.reduce=function(b){if(this===void 0||this===null)throw new TypeError;var c=Object(this),d=c.length>>>0,e=0,f;if(typeof b!="function")throw new TypeError;if(d==0&&arguments.length==1)throw new TypeError;if(arguments.length>=2)f=arguments[1];else do{if(e in c){f=c[e++];break}if(++e>=d)throw new TypeError}while(!0);while(e0?c.fn.concat.apply([],a):a}function O(a){return a.replace(/::/g,"/").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/_/g,"-").toLowerCase()}function P(a){return a in j?j[a]:j[a]=new RegExp("(^|\\s)"+a+"(\\s|$)")}function Q(a,b){return typeof b=="number"&&!l[O(a)]?b+"px":b}function R(a){var b,c;return i[a]||(b=h.createElement(a),h.body.appendChild(b),c=k(b,"").getPropertyValue("display"),b.parentNode.removeChild(b),c=="none"&&(c="block"),i[a]=c),i[a]}function S(a){return"children"in a?f.call(a.children):c.map(a.childNodes,function(a){if(a.nodeType==1)return a})}function T(c,d,e){for(b in d)e&&(J(d[b])||K(d[b]))?(J(d[b])&&!J(c[b])&&(c[b]={}),K(d[b])&&!K(c[b])&&(c[b]=[]),T(c[b],d[b],e)):d[b]!==a&&(c[b]=d[b])}function U(b,d){return d===a?c(b):c(b).filter(d)}function V(a,b,c,d){return F(b)?b.call(a,c,d):b}function W(a,b,c){c==null?a.removeAttribute(b):a.setAttribute(b,c)}function X(b,c){var d=b.className,e=d&&d.baseVal!==a;if(c===a)return e?d.baseVal:d;e?d.baseVal=c:b.className=c}function Y(a){var b;try{return a?a=="true"||(a=="false"?!1:a=="null"?null:isNaN(b=Number(a))?/^[\[\{]/.test(a)?c.parseJSON(a):a:b):a}catch(d){return a}}function Z(a,b){b(a);for(var c in a.childNodes)Z(a.childNodes[c],b)}var a,b,c,d,e=[],f=e.slice,g=e.filter,h=window.document,i={},j={},k=h.defaultView.getComputedStyle,l={"column-count":1,columns:1,"font-weight":1,"line-height":1,opacity:1,"z-index":1,zoom:1},m=/^\s*<(\w+|!)[^>]*>/,n=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,o=/^(?:body|html)$/i,p=["val","css","html","text","data","width","height","offset"],q=["after","prepend","before","append"],r=h.createElement("table"),s=h.createElement("tr"),t={tr:h.createElement("tbody"),tbody:r,thead:r,tfoot:r,td:s,th:s,"*":h.createElement("div")},u=/complete|loaded|interactive/,v=/^\.([\w-]+)$/,w=/^#([\w-]*)$/,x=/^[\w-]+$/,y={},z=y.toString,A={},B,C,D=h.createElement("div");return A.matches=function(a,b){if(!a||a.nodeType!==1)return!1;var c=a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.matchesSelector;if(c)return c.call(a,b);var d,e=a.parentNode,f=!e;return f&&(e=D).appendChild(a),d=~A.qsa(e,b).indexOf(a),f&&D.removeChild(a),d},B=function(a){return a.replace(/-+(.)?/g,function(a,b){return b?b.toUpperCase():""})},C=function(a){return g.call(a,function(b,c){return a.indexOf(b)==c})},A.fragment=function(b,d,e){b.replace&&(b=b.replace(n,"<$1>")),d===a&&(d=m.test(b)&&RegExp.$1),d in t||(d="*");var g,h,i=t[d];return i.innerHTML=""+b,h=c.each(f.call(i.childNodes),function(){i.removeChild(this)}),J(e)&&(g=c(h),c.each(e,function(a,b){p.indexOf(a)>-1?g[a](b):g.attr(a,b)})),h},A.Z=function(a,b){return a=a||[],a.__proto__=c.fn,a.selector=b||"",a},A.isZ=function(a){return a instanceof A.Z},A.init=function(b,d){if(!b)return A.Z();if(F(b))return c(h).ready(b);if(A.isZ(b))return b;var e;if(K(b))e=M(b);else if(I(b))e=[J(b)?c.extend({},b):b],b=null;else if(m.test(b))e=A.fragment(b.trim(),RegExp.$1,d),b=null;else{if(d!==a)return c(d).find(b);e=A.qsa(h,b)}return A.Z(e,b)},c=function(a,b){return A.init(a,b)},c.extend=function(a){var b,c=f.call(arguments,1);return typeof a=="boolean"&&(b=a,a=c.shift()),c.forEach(function(c){T(a,c,b)}),a},A.qsa=function(a,b){var c;return H(a)&&w.test(b)?(c=a.getElementById(RegExp.$1))?[c]:[]:a.nodeType!==1&&a.nodeType!==9?[]:f.call(v.test(b)?a.getElementsByClassName(RegExp.$1):x.test(b)?a.getElementsByTagName(b):a.querySelectorAll(b))},c.contains=function(a,b){return a!==b&&a.contains(b)},c.type=E,c.isFunction=F,c.isWindow=G,c.isArray=K,c.isPlainObject=J,c.isEmptyObject=function(a){var b;for(b in a)return!1;return!0},c.inArray=function(a,b,c){return e.indexOf.call(b,a,c)},c.camelCase=B,c.trim=function(a){return a.trim()},c.uuid=0,c.support={},c.expr={},c.map=function(a,b){var c,d=[],e,f;if(L(a))for(e=0;e=0?b:b+this.length]},toArray:function(){return this.get()},size:function(){return this.length},remove:function(){return this.each(function(){this.parentNode!=null&&this.parentNode.removeChild(this)})},each:function(a){return e.every.call(this,function(b,c){return a.call(b,c,b)!==!1}),this},filter:function(a){return F(a)?this.not(this.not(a)):c(g.call(this,function(b){return A.matches(b,a)}))},add:function(a,b){return c(C(this.concat(c(a,b))))},is:function(a){return this.length>0&&A.matches(this[0],a)},not:function(b){var d=[];if(F(b)&&b.call!==a)this.each(function(a){b.call(this,a)||d.push(this)});else{var e=typeof b=="string"?this.filter(b):L(b)&&F(b.item)?f.call(b):c(b);this.forEach(function(a){e.indexOf(a)<0&&d.push(a)})}return c(d)},has:function(a){return this.filter(function(){return I(a)?c.contains(this,a):c(this).find(a).size()})},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){var a=this[0];return a&&!I(a)?a:c(a)},last:function(){var a=this[this.length-1];return a&&!I(a)?a:c(a)},find:function(a){var b,d=this;return typeof a=="object"?b=c(a).filter(function(){var a=this;return e.some.call(d,function(b){return c.contains(b,a)})}):this.length==1?b=c(A.qsa(this[0],a)):b=this.map(function(){return A.qsa(this,a)}),b},closest:function(a,b){var d=this[0],e=!1;typeof a=="object"&&(e=c(a));while(d&&!(e?e.indexOf(d)>=0:A.matches(d,a)))d=d!==b&&!H(d)&&d.parentNode;return c(d)},parents:function(a){var b=[],d=this;while(d.length>0)d=c.map(d,function(a){if((a=a.parentNode)&&!H(a)&&b.indexOf(a)<0)return b.push(a),a});return U(b,a)},parent:function(a){return U(C(this.pluck("parentNode")),a)},children:function(a){return U(this.map(function(){return S(this)}),a)},contents:function(){return this.map(function(){return f.call(this.childNodes)})},siblings:function(a){return U(this.map(function(a,b){return g.call(S(b.parentNode),function(a){return a!==b})}),a)},empty:function(){return this.each(function(){this.innerHTML=""})},pluck:function(a){return c.map(this,function(b){return b[a]})},show:function(){return this.each(function(){this.style.display=="none"&&(this.style.display=null),k(this,"").getPropertyValue("display")=="none"&&(this.style.display=R(this.nodeName))})},replaceWith:function(a){return this.before(a).remove()},wrap:function(a){var b=F(a);if(this[0]&&!b)var d=c(a).get(0),e=d.parentNode||this.length>1;return this.each(function(f){c(this).wrapAll(b?a.call(this,f):e?d.cloneNode(!0):d)})},wrapAll:function(a){if(this[0]){c(this[0]).before(a=c(a));var b;while((b=a.children()).length)a=b.first();c(a).append(this)}return this},wrapInner:function(a){var b=F(a);return this.each(function(d){var e=c(this),f=e.contents(),g=b?a.call(this,d):a;f.length?f.wrapAll(g):e.append(g)})},unwrap:function(){return this.parent().each(function(){c(this).replaceWith(c(this).children())}),this},clone:function(){return this.map(function(){return this.cloneNode(!0)})},hide:function(){return this.css("display","none")},toggle:function(b){return this.each(function(){var d=c(this);(b===a?d.css("display")=="none":b)?d.show():d.hide()})},prev:function(a){return c(this.pluck("previousElementSibling")).filter(a||"*")},next:function(a){return c(this.pluck("nextElementSibling")).filter(a||"*")},html:function(b){return b===a?this.length>0?this[0].innerHTML:null:this.each(function(a){var d=this.innerHTML;c(this).empty().append(V(this,b,a,d))})},text:function(b){return b===a?this.length>0?this[0].textContent:null:this.each(function(){this.textContent=b})},attr:function(c,d){var e;return typeof c=="string"&&d===a?this.length==0||this[0].nodeType!==1?a:c=="value"&&this[0].nodeName=="INPUT"?this.val():!(e=this[0].getAttribute(c))&&c in this[0]?this[0][c]:e:this.each(function(a){if(this.nodeType!==1)return;if(I(c))for(b in c)W(this,b,c[b]);else W(this,c,V(this,d,a,this.getAttribute(c)))})},removeAttr:function(a){return this.each(function(){this.nodeType===1&&W(this,a)})},prop:function(b,c){return c===a?this[0]&&this[0][b]:this.each(function(a){this[b]=V(this,c,a,this[b])})},data:function(b,c){var d=this.attr("data-"+O(b),c);return d!==null?Y(d):a},val:function(b){return b===a?this[0]&&(this[0].multiple?c(this[0]).find("option").filter(function(a){return this.selected}).pluck("value"):this[0].value):this.each(function(a){this.value=V(this,b,a,this.value)})},offset:function(a){if(a)return this.each(function(b){var d=c(this),e=V(this,a,b,d.offset()),f=d.offsetParent().offset(),g={top:e.top-f.top,left:e.left-f.left};d.css("position")=="static"&&(g.position="relative"),d.css(g)});if(this.length==0)return null;var b=this[0].getBoundingClientRect();return{left:b.left+window.pageXOffset,top:b.top+window.pageYOffset,width:Math.round(b.width),height:Math.round(b.height)}},css:function(a,c){if(arguments.length<2&&typeof a=="string")return this[0]&&(this[0].style[B(a)]||k(this[0],"").getPropertyValue(a));var d="";if(E(a)=="string")!c&&c!==0?this.each(function(){this.style.removeProperty(O(a))}):d=O(a)+":"+Q(a,c);else for(b in a)!a[b]&&a[b]!==0?this.each(function(){this.style.removeProperty(O(b))}):d+=O(b)+":"+Q(b,a[b])+";";return this.each(function(){this.style.cssText+=";"+d})},index:function(a){return a?this.indexOf(c(a)[0]):this.parent().children().indexOf(this[0])},hasClass:function(a){return e.some.call(this,function(a){return this.test(X(a))},P(a))},addClass:function(a){return this.each(function(b){d=[];var e=X(this),f=V(this,a,b,e);f.split(/\s+/g).forEach(function(a){c(this).hasClass(a)||d.push(a)},this),d.length&&X(this,e+(e?" ":"")+d.join(" "))})},removeClass:function(b){return this.each(function(c){if(b===a)return X(this,"");d=X(this),V(this,b,c,d).split(/\s+/g).forEach(function(a){d=d.replace(P(a)," ")}),X(this,d.trim())})},toggleClass:function(b,d){return this.each(function(e){var f=c(this),g=V(this,b,e,X(this));g.split(/\s+/g).forEach(function(b){(d===a?!f.hasClass(b):d)?f.addClass(b):f.removeClass(b)})})},scrollTop:function(){if(!this.length)return;return"scrollTop"in this[0]?this[0].scrollTop:this[0].scrollY},position:function(){if(!this.length)return;var a=this[0],b=this.offsetParent(),d=this.offset(),e=o.test(b[0].nodeName)?{top:0,left:0}:b.offset();return d.top-=parseFloat(c(a).css("margin-top"))||0,d.left-=parseFloat(c(a).css("margin-left"))||0,e.top+=parseFloat(c(b[0]).css("border-top-width"))||0,e.left+=parseFloat(c(b[0]).css("border-left-width"))||0,{top:d.top-e.top,left:d.left-e.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||h.body;while(a&&!o.test(a.nodeName)&&c(a).css("position")=="static")a=a.offsetParent;return a})}},c.fn.detach=c.fn.remove,["width","height"].forEach(function(b){c.fn[b]=function(d){var e,f=this[0],g=b.replace(/./,function(a){return a[0].toUpperCase()});return d===a?G(f)?f["inner"+g]:H(f)?f.documentElement["offset"+g]:(e=this.offset())&&e[b]:this.each(function(a){f=c(this),f.css(b,V(this,d,a,f[b]()))})}}),q.forEach(function(a,b){var d=b%2;c.fn[a]=function(){var a,e=c.map(arguments,function(b){return a=E(b),a=="object"||a=="array"||b==null?b:A.fragment(b)}),f,g=this.length>1;return e.length<1?this:this.each(function(a,h){f=d?h:h.parentNode,h=b==0?h.nextSibling:b==1?h.firstChild:b==2?h:null,e.forEach(function(a){if(g)a=a.cloneNode(!0);else if(!f)return c(a).remove();Z(f.insertBefore(a,h),function(a){a.nodeName!=null&&a.nodeName.toUpperCase()==="SCRIPT"&&(!a.type||a.type==="text/javascript")&&!a.src&&window.eval.call(window,a.innerHTML)})})})},c.fn[d?a+"To":"insert"+(b?"Before":"After")]=function(b){return c(b)[a](this),this}}),A.Z.prototype=c.fn,A.uniq=C,A.deserializeValue=Y,c.zepto=A,c}();window.Zepto=Zepto,"$"in window||(window.$=Zepto),function(a){function b(a){var b=this.os={},c=this.browser={},d=a.match(/WebKit\/([\d.]+)/),e=a.match(/(Android)\s+([\d.]+)/),f=a.match(/(iPad).*OS\s([\d_]+)/),g=!f&&a.match(/(iPhone\sOS)\s([\d_]+)/),h=a.match(/(webOS|hpwOS)[\s\/]([\d.]+)/),i=h&&a.match(/TouchPad/),j=a.match(/Kindle\/([\d.]+)/),k=a.match(/Silk\/([\d._]+)/),l=a.match(/(BlackBerry).*Version\/([\d.]+)/),m=a.match(/(BB10).*Version\/([\d.]+)/),n=a.match(/(RIM\sTablet\sOS)\s([\d.]+)/),o=a.match(/PlayBook/),p=a.match(/Chrome\/([\d.]+)/)||a.match(/CriOS\/([\d.]+)/),q=a.match(/Firefox\/([\d.]+)/);if(c.webkit=!!d)c.version=d[1];e&&(b.android=!0,b.version=e[2]),g&&(b.ios=b.iphone=!0,b.version=g[2].replace(/_/g,".")),f&&(b.ios=b.ipad=!0,b.version=f[2].replace(/_/g,".")),h&&(b.webos=!0,b.version=h[2]),i&&(b.touchpad=!0),l&&(b.blackberry=!0,b.version=l[2]),m&&(b.bb10=!0,b.version=m[2]),n&&(b.rimtabletos=!0,b.version=n[2]),o&&(c.playbook=!0),j&&(b.kindle=!0,b.version=j[1]),k&&(c.silk=!0,c.version=k[1]),!k&&b.android&&a.match(/Kindle Fire/)&&(c.silk=!0),p&&(c.chrome=!0,c.version=p[1]),q&&(c.firefox=!0,c.version=q[1]),b.tablet=!!(f||o||e&&!a.match(/Mobile/)||q&&a.match(/Tablet/)),b.phone=!b.tablet&&!!(e||g||h||l||m||p&&a.match(/Android/)||p&&a.match(/CriOS\/([\d.]+)/)||q&&a.match(/Mobile/))}b.call(a,navigator.userAgent),a.__detect=b}(Zepto),function(a){function g(a){return a._zid||(a._zid=d++)}function h(a,b,d,e){b=i(b);if(b.ns)var f=j(b.ns);return(c[g(a)]||[]).filter(function(a){return a&&(!b.e||a.e==b.e)&&(!b.ns||f.test(a.ns))&&(!d||g(a.fn)===g(d))&&(!e||a.sel==e)})}function i(a){var b=(""+a).split(".");return{e:b[0],ns:b.slice(1).sort().join(" ")}}function j(a){return new RegExp("(?:^| )"+a.replace(" "," .* ?")+"(?: |$)")}function k(b,c,d){a.type(b)!="string"?a.each(b,d):b.split(/\s/).forEach(function(a){d(a,c)})}function l(a,b){return a.del&&(a.e=="focus"||a.e=="blur")||!!b}function m(a){return f[a]||a}function n(b,d,e,h,j,n){var o=g(b),p=c[o]||(c[o]=[]);k(d,e,function(c,d){var e=i(c);e.fn=d,e.sel=h,e.e in f&&(d=function(b){var c=b.relatedTarget;if(!c||c!==this&&!a.contains(this,c))return e.fn.apply(this,arguments)}),e.del=j&&j(d,c);var g=e.del||d;e.proxy=function(a){var c=g.apply(b,[a].concat(a.data));return c===!1&&(a.preventDefault(),a.stopPropagation()),c},e.i=p.length,p.push(e),b.addEventListener(m(e.e),e.proxy,l(e,n))})}function o(a,b,d,e,f){var i=g(a);k(b||"",d,function(b,d){h(a,b,d,e).forEach(function(b){delete c[i][b.i],a.removeEventListener(m(b.e),b.proxy,l(b,f))})})}function t(b){var c,d={originalEvent:b};for(c in b)!r.test(c)&&b[c]!==undefined&&(d[c]=b[c]);return a.each(s,function(a,c){d[a]=function(){return this[c]=p,b[a].apply(b,arguments)},d[c]=q}),d}function u(a){if(!("defaultPrevented"in a)){a.defaultPrevented=!1;var b=a.preventDefault;a.preventDefault=function(){this.defaultPrevented=!0,b.call(this)}}}var b=a.zepto.qsa,c={},d=1,e={},f={mouseenter:"mouseover",mouseleave:"mouseout"};e.click=e.mousedown=e.mouseup=e.mousemove="MouseEvents",a.event={add:n,remove:o},a.proxy=function(b,c){if(a.isFunction(b)){var d=function(){return b.apply(c,arguments)};return d._zid=g(b),d}if(typeof c=="string")return a.proxy(b[c],b);throw new TypeError("expected function")},a.fn.bind=function(a,b){return this.each(function(){n(this,a,b)})},a.fn.unbind=function(a,b){return this.each(function(){o(this,a,b)})},a.fn.one=function(a,b){return this.each(function(c,d){n(this,a,b,null,function(a,b){return function(){var c=a.apply(d,arguments);return o(d,b,a),c}})})};var p=function(){return!0},q=function(){return!1},r=/^([A-Z]|layer[XY]$)/,s={preventDefault:"isDefaultPrevented",stopImmediatePropagation:"isImmediatePropagationStopped",stopPropagation:"isPropagationStopped"};a.fn.delegate=function(b,c,d){return this.each(function(e,f){n(f,c,d,b,function(c){return function(d){var e,g=a(d.target).closest(b,f).get(0);if(g)return e=a.extend(t(d),{currentTarget:g,liveFired:f}),c.apply(g,[e].concat([].slice.call(arguments,1)))}})})},a.fn.undelegate=function(a,b,c){return this.each(function(){o(this,b,c,a)})},a.fn.live=function(b,c){return a(document.body).delegate(this.selector,b,c),this},a.fn.die=function(b,c){return a(document.body).undelegate(this.selector,b,c),this},a.fn.on=function(b,c,d){return!c||a.isFunction(c)?this.bind(b,c||d):this.delegate(c,b,d)},a.fn.off=function(b,c,d){return!c||a.isFunction(c)?this.unbind(b,c||d):this.undelegate(c,b,d)},a.fn.trigger=function(b,c){if(typeof b=="string"||a.isPlainObject(b))b=a.Event(b);return u(b),b.data=c,this.each(function(){"dispatchEvent"in this&&this.dispatchEvent(b)})},a.fn.triggerHandler=function(b,c){var d,e;return this.each(function(f,g){d=t(typeof b=="string"?a.Event(b):b),d.data=c,d.target=g,a.each(h(g,b.type||b),function(a,b){e=b.proxy(d);if(d.isImmediatePropagationStopped())return!1})}),e},"focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select keydown keypress keyup error".split(" ").forEach(function(b){a.fn[b]=function(a){return a?this.bind(b,a):this.trigger(b)}}),["focus","blur"].forEach(function(b){a.fn[b]=function(a){return a?this.bind(b,a):this.each(function(){try{this[b]()}catch(a){}}),this}}),a.Event=function(a,b){typeof a!="string"&&(b=a,a=b.type);var c=document.createEvent(e[a]||"Events"),d=!0;if(b)for(var f in b)f=="bubbles"?d=!!b[f]:c[f]=b[f];return c.initEvent(a,d,!0,null,null,null,null,null,null,null,null,null,null,null,null),c.isDefaultPrevented=function(){return this.defaultPrevented},c}}(Zepto),function($){function triggerAndReturn(a,b,c){var d=$.Event(b);return $(a).trigger(d,c),!d.defaultPrevented}function triggerGlobal(a,b,c,d){if(a.global)return triggerAndReturn(b||document,c,d)}function ajaxStart(a){a.global&&$.active++===0&&triggerGlobal(a,null,"ajaxStart")}function ajaxStop(a){a.global&&!--$.active&&triggerGlobal(a,null,"ajaxStop")}function ajaxBeforeSend(a,b){var c=b.context;if(b.beforeSend.call(c,a,b)===!1||triggerGlobal(b,c,"ajaxBeforeSend",[a,b])===!1)return!1;triggerGlobal(b,c,"ajaxSend",[a,b])}function ajaxSuccess(a,b,c){var d=c.context,e="success";c.success.call(d,a,e,b),triggerGlobal(c,d,"ajaxSuccess",[b,c,a]),ajaxComplete(e,b,c)}function ajaxError(a,b,c,d){var e=d.context;d.error.call(e,c,b,a),triggerGlobal(d,e,"ajaxError",[c,d,a]),ajaxComplete(b,c,d)}function ajaxComplete(a,b,c){var d=c.context;c.complete.call(d,b,a),triggerGlobal(c,d,"ajaxComplete",[b,c]),ajaxStop(c)}function empty(){}function mimeToDataType(a){return a&&(a=a.split(";",2)[0]),a&&(a==htmlType?"html":a==jsonType?"json":scriptTypeRE.test(a)?"script":xmlTypeRE.test(a)&&"xml")||"text"}function appendQuery(a,b){return(a+"&"+b).replace(/[&?]{1,2}/,"?")}function serializeData(a){a.processData&&a.data&&$.type(a.data)!="string"&&(a.data=$.param(a.data,a.traditional)),a.data&&(!a.type||a.type.toUpperCase()=="GET")&&(a.url=appendQuery(a.url,a.data))}function parseArguments(a,b,c,d){var e=!$.isFunction(b);return{url:a,data:e?b:undefined,success:e?$.isFunction(c)?c:undefined:b,dataType:e?d||c:c}}function serialize(a,b,c,d){var e,f=$.isArray(b);$.each(b,function(b,g){e=$.type(g),d&&(b=c?d:d+"["+(f?"":b)+"]"),!d&&f?a.add(g.name,g.value):e=="array"||!c&&e=="object"?serialize(a,g,c,b):a.add(b,g)})}var jsonpID=0,document=window.document,key,name,rscript=/)<[^<]*)*<\/script>/gi,scriptTypeRE=/^(?:text|application)\/javascript/i,xmlTypeRE=/^(?:text|application)\/xml/i,jsonType="application/json",htmlType="text/html",blankRE=/^\s*$/;$.active=0,$.ajaxJSONP=function(a){if("type"in a){var b="jsonp"+ ++jsonpID,c=document.createElement("script"),d=function(){clearTimeout(g),$(c).remove(),delete window[b]},e=function(c){d();if(!c||c=="timeout")window[b]=empty;ajaxError(null,c||"abort",f,a)},f={abort:e},g;return ajaxBeforeSend(f,a)===!1?(e("abort"),!1):(window[b]=function(b){d(),ajaxSuccess(b,f,a)},c.onerror=function(){e("error")},c.src=a.url.replace(/=\?/,"="+b),$("head").append(c),a.timeout>0&&(g=setTimeout(function(){e("timeout")},a.timeout)),f)}return $.ajax(a)},$.ajaxSettings={type:"GET",beforeSend:empty,success:empty,error:empty,complete:empty,context:null,global:!0,xhr:function(){return new window.XMLHttpRequest},accepts:{script:"text/javascript, application/javascript",json:jsonType,xml:"application/xml, text/xml",html:htmlType,text:"text/plain"},crossDomain:!1,timeout:0,processData:!0,cache:!0},$.ajax=function(options){var settings=$.extend({},options||{});for(key in $.ajaxSettings)settings[key]===undefined&&(settings[key]=$.ajaxSettings[key]);ajaxStart(settings),settings.crossDomain||(settings.crossDomain=/^([\w-]+:)?\/\/([^\/]+)/.test(settings.url)&&RegExp.$2!=window.location.host),settings.url||(settings.url=window.location.toString()),serializeData(settings),settings.cache===!1&&(settings.url=appendQuery(settings.url,"_="+Date.now()));var dataType=settings.dataType,hasPlaceholder=/=\?/.test(settings.url);if(dataType=="jsonp"||hasPlaceholder)return hasPlaceholder||(settings.url=appendQuery(settings.url,"callback=?")),$.ajaxJSONP(settings);var mime=settings.accepts[dataType],baseHeaders={},protocol=/^([\w-]+:)\/\//.test(settings.url)?RegExp.$1:window.location.protocol,xhr=settings.xhr(),abortTimeout;settings.crossDomain||(baseHeaders["X-Requested-With"]="XMLHttpRequest"),mime&&(baseHeaders.Accept=mime,mime.indexOf(",")>-1&&(mime=mime.split(",",2)[0]),xhr.overrideMimeType&&xhr.overrideMimeType(mime));if(settings.contentType||settings.contentType!==!1&&settings.data&&settings.type.toUpperCase()!="GET")baseHeaders["Content-Type"]=settings.contentType||"application/x-www-form-urlencoded";settings.headers=$.extend(baseHeaders,settings.headers||{}),xhr.onreadystatechange=function(){if(xhr.readyState==4){xhr.onreadystatechange=empty,clearTimeout(abortTimeout);var result,error=!1;if(xhr.status>=200&&xhr.status<300||xhr.status==304||xhr.status==0&&protocol=="file:"){dataType=dataType||mimeToDataType(xhr.getResponseHeader("content-type")),result=xhr.responseText;try{dataType=="script"?(1,eval)(result):dataType=="xml"?result=xhr.responseXML:dataType=="json"&&(result=blankRE.test(result)?null:$.parseJSON(result))}catch(e){error=e}error?ajaxError(error,"parsererror",xhr,settings):ajaxSuccess(result,xhr,settings)}else ajaxError(null,xhr.status?"error":"abort",xhr,settings)}};var async="async"in settings?settings.async:!0;xhr.open(settings.type,settings.url,async);for(name in settings.headers)xhr.setRequestHeader(name,settings.headers[name]);return ajaxBeforeSend(xhr,settings)===!1?(xhr.abort(),!1):(settings.timeout>0&&(abortTimeout=setTimeout(function(){xhr.onreadystatechange=empty,xhr.abort(),ajaxError(null,"timeout",xhr,settings)},settings.timeout)),xhr.send(settings.data?settings.data:null),xhr)},$.get=function(a,b,c,d){return $.ajax(parseArguments.apply(null,arguments))},$.post=function(a,b,c,d){var e=parseArguments.apply(null,arguments);return e.type="POST",$.ajax(e)},$.getJSON=function(a,b,c){var d=parseArguments.apply(null,arguments);return d.dataType="json",$.ajax(d)},$.fn.load=function(a,b,c){if(!this.length)return this;var d=this,e=a.split(/\s/),f,g=parseArguments(a,b,c),h=g.success;return e.length>1&&(g.url=e[0],f=e[1]),g.success=function(a){d.html(f?$("
").html(a.replace(rscript,"")).find(f):a),h&&h.apply(d,arguments)},$.ajax(g),this};var escape=encodeURIComponent;$.param=function(a,b){var c=[];return c.add=function(a,b){this.push(escape(a)+"="+escape(b))},serialize(c,a,b),c.join("&").replace(/%20/g,"+")}}(Zepto),function(a){a.fn.serializeArray=function(){var b=[],c;return a(Array.prototype.slice.call(this.get(0).elements)).each(function(){c=a(this);var d=c.attr("type");this.nodeName.toLowerCase()!="fieldset"&&!this.disabled&&d!="submit"&&d!="reset"&&d!="button"&&(d!="radio"&&d!="checkbox"||this.checked)&&b.push({name:c.attr("name"),value:c.val()})}),b},a.fn.serialize=function(){var a=[];return this.serializeArray().forEach(function(b){a.push(encodeURIComponent(b.name)+"="+encodeURIComponent(b.value))}),a.join("&")},a.fn.submit=function(b){if(b)this.bind("submit",b);else if(this.length){var c=a.Event("submit");this.eq(0).trigger(c),c.defaultPrevented||this.get(0).submit()}return this}}(Zepto),function(a,b){function s(a){return t(a.replace(/([a-z])([A-Z])/,"$1-$2"))}function t(a){return a.toLowerCase()}function u(a){return d?d+a:t(a)}var c="",d,e,f,g={Webkit:"webkit",Moz:"",O:"o",ms:"MS"},h=window.document,i=h.createElement("div"),j=/^((translate|rotate|scale)(X|Y|Z|3d)?|matrix(3d)?|perspective|skew(X|Y)?)$/i,k,l,m,n,o,p,q,r={};a.each(g,function(a,e){if(i.style[a+"TransitionProperty"]!==b)return c="-"+t(a)+"-",d=e,!1}),k=c+"transform",r[l=c+"transition-property"]=r[m=c+"transition-duration"]=r[n=c+"transition-timing-function"]=r[o=c+"animation-name"]=r[p=c+"animation-duration"]=r[q=c+"animation-timing-function"]="",a.fx={off:d===b&&i.style.transitionProperty===b,speeds:{_default:400,fast:200,slow:600},cssPrefix:c,transitionEnd:u("TransitionEnd"),animationEnd:u("AnimationEnd")},a.fn.animate=function(b,c,d,e){return a.isPlainObject(c)&&(d=c.easing,e=c.complete,c=c.duration),c&&(c=(typeof c=="number"?c:a.fx.speeds[c]||a.fx.speeds._default)/1e3),this.anim(b,c,d,e)},a.fn.anim=function(c,d,e,f){var g,h={},i,t="",u=this,v,w=a.fx.transitionEnd;d===b&&(d=.4),a.fx.off&&(d=0);if(typeof c=="string")h[o]=c,h[p]=d+"s",h[q]=e||"linear",w=a.fx.animationEnd;else{i=[];for(g in c)j.test(g)?t+=g+"("+c[g]+") ":(h[g]=c[g],i.push(s(g)));t&&(h[k]=t,i.push(k)),d>0&&typeof c=="object"&&(h[l]=i.join(", "),h[m]=d+"s",h[n]=e||"linear")}return v=function(b){if(typeof b!="undefined"){if(b.target!==b.currentTarget)return;a(b.target).unbind(w,v)}a(this).css(r),f&&f.call(this)},d>0&&this.bind(w,v),this.size()&&this.get(0).clientLeft,this.css(h),d<=0&&setTimeout(function(){u.each(function(){v.call(this)})},0),this},i=null}(Zepto) diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/TimeCheck/TimeCheck.ino b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/TimeCheck/TimeCheck.ino new file mode 100644 index 000000000..0403aa49a --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/TimeCheck/TimeCheck.ino @@ -0,0 +1,88 @@ +/* + Time Check + + Gets the time from Linux via Bridge then parses out hours, + minutes and seconds using a YunShield/Yún. + + created 27 May 2013 + modified 21 June 2013 + By Tom Igoe + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/TimeCheck + + */ + + +#include + +Process date; // process used to get the date +int hours, minutes, seconds; // for the results +int lastSecond = -1; // need an impossible value for comparison + +void setup() { + Bridge.begin(); // initialize Bridge + SerialUSB.begin(9600); // initialize serial + + while (!Serial); // wait for Serial Monitor to open + SerialUSB.println("Time Check"); // Title of sketch + + // run an initial date process. Should return: + // hh:mm:ss : + if (!date.running()) { + date.begin("date"); + date.addParameter("+%T"); + date.run(); + } +} + +void loop() { + + if (lastSecond != seconds) { // if a second has passed + // print the time: + if (hours <= 9) { + SerialUSB.print("0"); // adjust for 0-9 + } + SerialUSB.print(hours); + SerialUSB.print(":"); + if (minutes <= 9) { + SerialUSB.print("0"); // adjust for 0-9 + } + SerialUSB.print(minutes); + SerialUSB.print(":"); + if (seconds <= 9) { + SerialUSB.print("0"); // adjust for 0-9 + } + SerialUSB.println(seconds); + + // restart the date process: + if (!date.running()) { + date.begin("date"); + date.addParameter("+%T"); + date.run(); + } + } + + //if there's a result from the date process, parse it: + while (date.available() > 0) { + // get the result of the date process (should be hh:mm:ss): + String timeString = date.readString(); + + // find the colons: + int firstColon = timeString.indexOf(":"); + int secondColon = timeString.lastIndexOf(":"); + + // get the substrings for hour, minute second: + String hourString = timeString.substring(0, firstColon); + String minString = timeString.substring(firstColon + 1, secondColon); + String secString = timeString.substring(secondColon + 1); + + // convert to ints,saving the previous second: + hours = hourString.toInt(); + minutes = minString.toInt(); + lastSecond = seconds; // save to do a time comparison + seconds = secString.toInt(); + } + +} diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/WiFiStatus/WiFiStatus.ino b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/WiFiStatus/WiFiStatus.ino new file mode 100644 index 000000000..198761ba2 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/WiFiStatus/WiFiStatus.ino @@ -0,0 +1,51 @@ +/* + WiFi Status + + This sketch runs a script called "pretty-wifi-info.lua" + installed on your Yún in folder /usr/bin. + It prints information about the status of your wifi connection. + + It uses Serial to print, so you need to connect your YunShield/Yún to your + computer using a USB cable and select the appropriate port from + the Port menu + + created 18 June 2013 + By Federico Fissore + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/YunWiFiStatus + + */ + +#include + +void setup() { + SerialUSB.begin(9600); // initialize serial communication + while (!SerialUSB); // do nothing until the serial monitor is opened + + SerialUSB.println("Starting bridge...\n"); + pinMode(13, OUTPUT); + digitalWrite(13, LOW); + Bridge.begin(); // make contact with the linux processor + digitalWrite(13, HIGH); // Led on pin 13 turns on when the bridge is ready + + delay(2000); // wait 2 seconds +} + +void loop() { + Process wifiCheck; // initialize a new process + + wifiCheck.runShellCommand("/usr/bin/pretty-wifi-info.lua"); // command you want to run + + // while there's any characters coming back from the + // process, print them to the serial monitor: + while (wifiCheck.available() > 0) { + char c = wifiCheck.read(); + SerialUSB.print(c); + } + + SerialUSB.println(); + + delay(5000); +} diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/YunFirstConfig/YunFirstConfig.ino b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/YunFirstConfig/YunFirstConfig.ino new file mode 100644 index 000000000..72bf9e00b --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/YunFirstConfig/YunFirstConfig.ino @@ -0,0 +1,328 @@ + +/* + Arduino Yún First configuration sketch + + Configures the YunShield/Yún WiFi and infos via the Bridge + Works correctly if Line Ending is set as "NewLine" + If your board has two USB ports, use the Native one + + The circuit: + Arduino YunShield + (or any Yun model with firmware > 1.6.1) + + created March 2016 + by Arduino LLC + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/YunFirstConfig +*/ + +#include + +#define MAX_WIFI_LIST 10 + +String networks[MAX_WIFI_LIST]; +String yunName; +String yunPassword; + +void setup() { + SERIAL_PORT_USBVIRTUAL.begin(9600); // initialize serial communication + while (!SERIAL_PORT_USBVIRTUAL); // do nothing until the serial monitor is opened + + SERIAL_PORT_USBVIRTUAL.println(F("Hi! Nice to see you!")); + SERIAL_PORT_USBVIRTUAL.println(F("I'm your YunShield assistant sketch")); + SERIAL_PORT_USBVIRTUAL.println(F("I'll help you configuring your Yun in a matter of minutes")); + + SERIAL_PORT_USBVIRTUAL.println(F("Let's start by communicating with the Linux processor")); + SERIAL_PORT_USBVIRTUAL.println(F("When LED (L13) will light up we'll be ready to go!")); + SERIAL_PORT_USBVIRTUAL.println(F("Waiting...")); + SERIAL_PORT_USBVIRTUAL.println(F("(in the meanwhile, if you are using the IDE's serial monitor, make sure that it's configured to send a \"Newline\")\n")); + pinMode(13, OUTPUT); + digitalWrite(13, LOW); + Bridge.begin(); // make contact with the linux processor + digitalWrite(13, HIGH); // Led on pin 13 turns on when the bridge is ready + + // Recover if the board is in AP mode - unused + Process wifiList; + bool master = false; + wifiList.runShellCommand(F("iwinfo | grep \"Mode: Master\"")); + while (wifiList.available() > 0) { + wifiList.read(); + master = true; + } + + // Get the list of reachable networks + wifiList.runShellCommand(F("iwinfo wlan0 scan | grep ESSID | cut -d\"\\\"\" -f2")); + + uint8_t num_networks = 0; + uint8_t i = 0; + char c; + bool dropNet = false; + + networks[0].reserve(32); + + while (wifiList.available() > 0) { + c = wifiList.read(); + if (c != '\n') { + networks[i] += c; + } else { + // check if we already found networks[i] and eventually drop it + for (uint8_t s = 0; s < i; s++) { + if (networks[i].equals(networks[s])) { + dropNet = true; + } + } + if (i <= MAX_WIFI_LIST && dropNet == false) { + networks[i++].reserve(32); + } else { + dropNet = false; + networks[i]=""; + } + } + } + + num_networks = i; + + String encryption; + String password; + int chose = 0; + + // If networks number is 0, start manual configuration + if (num_networks == 0) { + SERIAL_PORT_USBVIRTUAL.println(F("Oops, it seems that you have no WiFi network available")); + SERIAL_PORT_USBVIRTUAL.println(F("Let's configure it manually")); + SERIAL_PORT_USBVIRTUAL.println(F("SSID of the network you want to connect to: ")); + networks[0] = getUserInput(networks[0], false); + SERIAL_PORT_USBVIRTUAL.println(F("Password for the network you want to connect to: ")); + password = getUserInput(password, true); + SERIAL_PORT_USBVIRTUAL.print(F("Encryption (eg WPA, WPA2, WEP): ")); + encryption = getUserInput(encryption, false); + } else { + // else print them prepending a number + SERIAL_PORT_USBVIRTUAL.print(F("It looks like you have ")); + SERIAL_PORT_USBVIRTUAL.print(num_networks); + SERIAL_PORT_USBVIRTUAL.println(F(" networks around you ")); + SERIAL_PORT_USBVIRTUAL.println(F("Which one do you want to connect to?\n")); + for (i = 0; i < num_networks && i < MAX_WIFI_LIST; i++) { + SERIAL_PORT_USBVIRTUAL.print(i); + SERIAL_PORT_USBVIRTUAL.println(") " + networks[i]); + } + String selection; + selection = getUserInput(selection, false); + chose = atoi(selection.c_str()); + } + + // Extract the selected network security + bool openNet = false; + wifiList.runShellCommand("iwinfo wlan0 scan | grep \"" + networks[chose] + "\" -A5 | grep Encryption | cut -f2 -d\":\""); + while (wifiList.available() > 0) { + c = wifiList.read(); + encryption += c; + } + + if (encryption.indexOf("none") >= 0) { + openNet = true; + encryption = "none"; + } + if (encryption.indexOf("WPA2") >= 0) { + encryption = "psk2"; + } + if (encryption.indexOf("WPA") >= 0) { + encryption = "psk"; + } + if (encryption.indexOf("WEP") >= 0) { + encryption = "wep"; + } + + if (openNet == false && password.length() == 0) { + SERIAL_PORT_USBVIRTUAL.print(F("It looks like you need a password to connect to ")); + SERIAL_PORT_USBVIRTUAL.println(networks[chose]); + SERIAL_PORT_USBVIRTUAL.print(F("Write it here: ")); + password = getUserInput(password, true); + } + + // Change hostname/root password + SERIAL_PORT_USBVIRTUAL.println(F("We are almost done! Give a name and a password to your Yun")); + SERIAL_PORT_USBVIRTUAL.print(F("Name: ")); + yunName = getUserInput(yunName, false); + SERIAL_PORT_USBVIRTUAL.print(F("Password: ")); + yunPassword = getUserInput(yunPassword, true); + + // Select a country code + String countryCode; + SERIAL_PORT_USBVIRTUAL.println(F("One last question: where do you live?")); + SERIAL_PORT_USBVIRTUAL.print(F("Insert a two letters county code (eg IT, US, DE): ")); + countryCode = getUserInput(countryCode, false); + + yunName.trim(); + yunPassword.trim(); + networks[chose].trim(); + password.trim(); + countryCode.trim(); + + // Configure the Yun with user provided strings + wifiConfig(yunName, yunPassword, networks[chose], password, "YUN" + yunName + "AP", countryCode, encryption); + + SERIAL_PORT_USBVIRTUAL.print(F("Waiting for the Yun to connect to the network")); +} + +bool Connected = false; +bool serialTerminalMode = false; +int runs = 0; + +void loop() { + if (!serialTerminalMode) { + String resultStr = ""; + + if (!Connected) { + SERIAL_PORT_USBVIRTUAL.print("."); + runs++; + } + + // If it takes more than 20 seconds to connect, stop trying + if (runs > 20) { + SERIAL_PORT_USBVIRTUAL.println(""); + SERIAL_PORT_USBVIRTUAL.println(F("We couldn't connect to the network.")); + SERIAL_PORT_USBVIRTUAL.println(F("Restart the board if you want to execute the wizard again")); + resultStr = getUserInput(resultStr, false); + } + + // Check if we have an IP address + Process wifiCheck; + wifiCheck.runShellCommand(F("/usr/bin/pretty-wifi-info.lua | grep \"IP address\" | cut -f2 -d\":\" | cut -f1 -d\"/\"" )); // command you want to run + while (wifiCheck.available() > 0) { + char c = wifiCheck.read(); + resultStr += c; + } + + delay(1000); + + if (resultStr != "") { + // We got an IP, freeze the loop, display the value and "spawn" a serial terminal + Connected = true; + resultStr.trim(); + SERIAL_PORT_USBVIRTUAL.println(""); + SERIAL_PORT_USBVIRTUAL.print(F("\nGreat! You can now reach your Yun from a browser typing http://")); + SERIAL_PORT_USBVIRTUAL.println(resultStr); + SERIAL_PORT_USBVIRTUAL.print(F("Press 'Enter' key twice to start a serial terminal")); + resultStr = getUserInput(resultStr, false); + serialTerminalMode = true; + //startSerialTerminal(); + SERIAL_PORT_HARDWARE.write((uint8_t *)"\xff\0\0\x05XXXXX\x7f\xf9", 11); // send "bridge shutdown" command + delay(100); + SERIAL_PORT_HARDWARE.println("\nreset\n\n"); + SERIAL_PORT_HARDWARE.flush(); + SERIAL_PORT_HARDWARE.println("\nreset\n\n"); + SERIAL_PORT_HARDWARE.write((uint8_t *)"\n", 1); + } + + } else { + loopSerialTerminal(); + } +} + +String getUserInput(String out, bool obfuscated) { + /* + while (SerialUSB.available() <= 0) {} + while (SerialUSB.available() > 0) { + char c = SerialUSB.read(); + out += c; + } + return out; + */ + while (SERIAL_PORT_USBVIRTUAL.available() <= 0) {} + while (1) { + char c = SERIAL_PORT_USBVIRTUAL.read(); + if (c == '\n' || c == '\r') + break; + else { + if (c != -1) { + out += c; + if (obfuscated) + SERIAL_PORT_USBVIRTUAL.print("*"); + else + SERIAL_PORT_USBVIRTUAL.print(c); + } + } + } + SERIAL_PORT_USBVIRTUAL.println(""); + return out; +} + +void wifiConfig(String yunName, String yunPsw, String wifissid, String wifipsw, String wifiAPname, String countryCode, String encryption) { + Process p; + + p.runShellCommand("blink-start 100"); //start the blue blink + + p.runShellCommand("hostname " + yunName); //change the current hostname + p.runShellCommand("uci set system.@system[0].hostname='" + yunName + "'"); //change teh hostname in uci + + p.runShellCommand("uci set arduino.@arduino[0].access_point_wifi_name='" + wifiAPname + "'"); + + //this block resets the wifi psw + p.runShellCommand("uci set wireless.@wifi-iface[0].encryption='" + encryption + "'"); + p.runShellCommand("uci set wireless.@wifi-iface[0].mode='sta'\n"); + p.runShellCommand("uci set wireless.@wifi-iface[0].ssid='" + wifissid + "'"); + p.runShellCommand("uci set wireless.@wifi-iface[0].key='" + wifipsw + "'"); + p.runShellCommand("uci set wireless.radio0.channel='auto'"); + p.runShellCommand("uci set wireless.radio0.country='" + countryCode + "'"); + p.runShellCommand("uci delete network.lan.ipaddr"); + p.runShellCommand("uci delete network.lan.netmask"); + p.runShellCommand("uci set network.lan.proto='dhcp'"); + + p.runShellCommand("echo -e \"" + yunPsw + "\n" + yunPsw + "\" | passwd root"); //change the passwors + p.runShellCommand("uci commit"); //save the mods done via UCI + p.runShellCommand("blink-stop"); //start the blue blink + + p.runShellCommand("wifi "); +} + +long linuxBaud = 250000; + +void startSerialTerminal() { + SERIAL_PORT_USBVIRTUAL.begin(115200); // open serial connection via USB-Serial + SERIAL_PORT_HARDWARE.begin(linuxBaud); // open serial connection to Linux +} + +boolean commandMode = false; +void loopSerialTerminal() { + // copy from USB-CDC to UART + int c = SERIAL_PORT_USBVIRTUAL.read(); // read from USB-CDC + if (c != -1) { // got anything? + if (commandMode == false) { // if we aren't in command mode... + if (c == '~') { // Tilde '~' key pressed? + commandMode = true; // enter in command mode + } else { + SERIAL_PORT_HARDWARE.write(c); // otherwise write char to UART + } + } else { // if we are in command mode... + if (c == '0') { // '0' key pressed? + SERIAL_PORT_HARDWARE.begin(57600); // set speed to 57600 + SERIAL_PORT_USBVIRTUAL.println("Speed set to 57600"); + } else if (c == '1') { // '1' key pressed? + SERIAL_PORT_HARDWARE.begin(115200); // set speed to 115200 + SERIAL_PORT_USBVIRTUAL.println("Speed set to 115200"); + } else if (c == '2') { // '2' key pressed? + SERIAL_PORT_HARDWARE.begin(250000); // set speed to 250000 + SERIAL_PORT_USBVIRTUAL.println("Speed set to 250000"); + } else if (c == '3') { // '3' key pressed? + SERIAL_PORT_HARDWARE.begin(500000); // set speed to 500000 + SERIAL_PORT_USBVIRTUAL.println("Speed set to 500000"); + } else if (c == '~') { // '~` key pressed? + SERIAL_PORT_HARDWARE.write((uint8_t *)"\xff\0\0\x05XXXXX\x7f\xf9", 11); // send "bridge shutdown" command + SERIAL_PORT_USBVIRTUAL.println("Sending bridge's shutdown command"); + } else { // any other key pressed? + SERIAL_PORT_HARDWARE.write('~'); // write '~' to UART + SERIAL_PORT_HARDWARE.write(c); // write char to UART + } + commandMode = false; // in all cases exit from command mode + } + } + + // copy from UART to USB-CDC + c = SERIAL_PORT_HARDWARE.read(); // read from UART + if (c != -1) { // got anything? + SERIAL_PORT_USBVIRTUAL.write(c); // write to USB-CDC + } +} diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/YunSerialTerminal/YunSerialTerminal.ino b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/YunSerialTerminal/YunSerialTerminal.ino new file mode 100644 index 000000000..641c1e9f0 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/examples/YunSerialTerminal/YunSerialTerminal.ino @@ -0,0 +1,82 @@ +/* + Arduino Yún USB-to-Serial + + Allows you to use the YunShield/Yún processor as a + serial terminal for the Linux side on the Yún. + + Upload this to a YunShield/Yún via serial (not WiFi) then open + the serial monitor at 115200 to see the boot process of Linux. + You can also use the serial monitor as a basic command line + interface for Linux using this sketch. + + From the serial monitor the following commands can be issued: + + '~' followed by '0' -> Set the UART speed to 57600 baud + '~' followed by '1' -> Set the UART speed to 115200 baud + '~' followed by '2' -> Set the UART speed to 250000 baud + '~' followed by '3' -> Set the UART speed to 500000 baud + '~' followed by '~' -> Sends the bridge's shutdown command to + obtain the console. + + The circuit: + YunShield/Yún + + created March 2013 + by Massimo Banzi + modified by Cristian Maglie + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/YunSerialTerminal + +*/ + +long linuxBaud = 250000; + +void setup() { + SERIAL_PORT_USBVIRTUAL.begin(115200); // open serial connection via USB-Serial + SERIAL_PORT_HARDWARE.begin(linuxBaud); // open serial connection to Linux +} + +boolean commandMode = false; + +void loop() { + // copy from USB-CDC to UART + int c = SERIAL_PORT_USBVIRTUAL.read(); // read from USB-CDC + if (c != -1) { // got anything? + if (commandMode == false) { // if we aren't in command mode... + if (c == '~') { // Tilde '~' key pressed? + commandMode = true; // enter in command mode + } else { + SERIAL_PORT_HARDWARE.write(c); // otherwise write char to UART + } + } else { // if we are in command mode... + if (c == '0') { // '0' key pressed? + SERIAL_PORT_HARDWARE.begin(57600); // set speed to 57600 + SERIAL_PORT_USBVIRTUAL.println("Speed set to 57600"); + } else if (c == '1') { // '1' key pressed? + SERIAL_PORT_HARDWARE.begin(115200); // set speed to 115200 + SERIAL_PORT_USBVIRTUAL.println("Speed set to 115200"); + } else if (c == '2') { // '2' key pressed? + SERIAL_PORT_HARDWARE.begin(250000); // set speed to 250000 + SERIAL_PORT_USBVIRTUAL.println("Speed set to 250000"); + } else if (c == '3') { // '3' key pressed? + SERIAL_PORT_HARDWARE.begin(500000); // set speed to 500000 + SERIAL_PORT_USBVIRTUAL.println("Speed set to 500000"); + } else if (c == '~') { // '~` key pressed? + SERIAL_PORT_HARDWARE.write((uint8_t *)"\xff\0\0\x05XXXXX\x7f\xf9", 11); // send "bridge shutdown" command + SERIAL_PORT_USBVIRTUAL.println("Sending bridge's shutdown command"); + } else { // any other key pressed? + SERIAL_PORT_HARDWARE.write('~'); // write '~' to UART + SERIAL_PORT_HARDWARE.write(c); // write char to UART + } + commandMode = false; // in all cases exit from command mode + } + } + + // copy from UART to USB-CDC + c = SERIAL_PORT_HARDWARE.read(); // read from UART + if (c != -1) { // got anything? + SERIAL_PORT_USBVIRTUAL.write(c); // write to USB-CDC + } +} diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/keywords.txt b/app/testdata/libraries/Bridge_1.7.0/Bridge/keywords.txt new file mode 100644 index 000000000..09fee8883 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/keywords.txt @@ -0,0 +1,92 @@ +####################################### +# Syntax Coloring Map For Bridge +####################################### + +####################################### +# Class (KEYWORD1) +####################################### + +Bridge KEYWORD1 YunBridgeLibrary +FileIO KEYWORD4 YunFileIOConstructor +FileSystem KEYWORD1 YunFileIOConstructor +Console KEYWORD1 YunConsoleConstructor +Process KEYWORD1 YunProcessConstructor +Mailbox KEYWORD1 YunMailboxConstructor +HttpClient KEYWORD1 YunHttpClientConstructor +YunServer KEYWORD1 YunServerConstructor +YunClient KEYWORD1 YunClientConstructor +BridgeServer KEYWORD1 YunServerConstructor +BridgeClient KEYWORD1 YunClientConstructor +BridgeSSLClient KEYWORD1 YunClientConstructor + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +# methods names in commond +begin KEYWORD2 +end KEYWORD2 +available KEYWORD2 +read KEYWORD2 +peek KEYWORD2 +write KEYWORD2 +flush KEYWORD2 +bool KEYWORD2 + +# Bridge Class +transfer KEYWORD2 +put KEYWORD2 +get KEYWORD2 + +# Console Class +buffer KEYWORD2 +noBuffer KEYWORD2 +connected KEYWORD2 + +# FileIO Class +File KEYWORD2 +BridgeFile KEYWORD2 +seek KEYWORD2 +position KEYWORD2 +size KEYWORD2 +close KEYWORD2 +name KEYWORD2 +isDirectory KEYWORD2 +openNextFile KEYWORD2 +rewindDirectory KEYWORD2 + +# Process Class +addParameter KEYWORD2 +runAsynchronously KEYWORD2 +run KEYWORD2 +running KEYWORD2 +exitValue KEYWORD2 +runShellCommand KEYWORD2 +runShellCommandAsynchronously KEYWORD2 + +# Mailbox Class +readMessage KEYWORD2 +writeMessage KEYWORD2 +writeJSON KEYWORD2 +messageAvailable KEYWORD2 + +# HttpClient Class +getAsynchronously KEYWORD2 +ready KEYWORD2 +getResult KEYWORD2 + +# BridgeServer Class +accept KEYWORD2 +stop KEYWORD2 +connect KEYWORD2 +connectSSL KEYWORD2 +connected KEYWORD2 + + +####################################### +# Constants (LITERAL1) +####################################### + +FILE_READ LITERAL1 +FILE_WRITE LITERAL1 +FILE_APPEND LITERAL1 diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/library.properties b/app/testdata/libraries/Bridge_1.7.0/Bridge/library.properties new file mode 100644 index 000000000..f49ff5e4f --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/library.properties @@ -0,0 +1,10 @@ +name=Bridge +version=1.7.0 +author=Arduino +maintainer=Arduino +sentence=Enables the communication between the Linux processor and the microcontroller. For Arduino/Genuino Yún, Yún Shield and TRE only. +paragraph=The Bridge library feature: access to the shared storage, run and manage linux processes, open a remote console, access to the linux file system, including the SD card, enstablish http clients or servers. +category=Communication +url=http://www.arduino.cc/en/Reference/YunBridgeLibrary +architectures=* +dot_a_linkage=true diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/src/Bridge.cpp b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/Bridge.cpp new file mode 100644 index 000000000..54c9fef09 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/Bridge.cpp @@ -0,0 +1,312 @@ +/* + Copyright (c) 2013 Arduino LLC. 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 "Bridge.h" + +BridgeClass::BridgeClass(Stream &_stream) : + index(0), stream(_stream), started(false), max_retries(0) { + // Empty +} + +void BridgeClass::begin() { + if (started) + return; + started = true; + + // Wait for U-boot to finish startup + do { + dropAll(); + delay(1000); + } while (stream.available() > 0); + + while (true) { + // Bridge interrupt: + // - Ask the bridge to close itself + uint8_t quit_cmd[] = {'X', 'X', 'X', 'X', 'X'}; + max_retries = 1; + transfer(quit_cmd, 5); + + // Bridge startup: + // - If the bridge is not running starts it safely + stream.print(CTRL_C); + delay(250); + stream.print(F("\n")); + delay(250); + stream.print(F("\n")); + delay(500); + // Wait for OpenWRT message + // "Press enter to activate console" + stream.print(F("run-bridge\n")); + delay(500); + dropAll(); + + // Reset the brigde to check if it is running + uint8_t cmd[] = {'X', 'X', '1', '0', '0'}; + uint8_t res[4]; + max_retries = 50; + uint16_t l = transfer(cmd, 5, res, 4); + if (l == TRANSFER_TIMEOUT) { + // Bridge didn't start... + // Maybe the board is starting-up? + + // Wait and retry + delay(1000); + continue; + } + if (res[0] != 0) + while (true); + + // Detect bridge version + if (l == 4) { + bridgeVersion = (res[1]-'0')*100 + (res[2]-'0')*10 + (res[3]-'0'); + } else { + // Bridge v1.0.0 didn't send any version info + bridgeVersion = 100; + } + + max_retries = 50; + return; + } +} + +void BridgeClass::end() { + + while (true) { + // Bridge interrupt: + // - Ask the bridge to close itself + uint8_t quit_cmd[] = {'X', 'X', 'X', 'X', 'X'}; + max_retries = 1; + transfer(quit_cmd, 5); + delay(100); + stream.print(CTRL_C); + delay(250); + stream.print(F("cd \n")); + //expect a shell + bool done = false; + delay(100); + while (stream.available()) { + char c = stream.read(); + if (c == '#') { + done = true; + break; + } + } + if (done) { + stream.print(F("reset\n")); + break; + } + } + delay(100); + dropAll(); +} + +void BridgeClass::put(const char *key, const char *value) { + // TODO: do it in a more efficient way + String cmd = "D"; + uint8_t res[1]; + cmd += key; + cmd += "\xFE"; + cmd += value; + transfer((uint8_t*)cmd.c_str(), cmd.length(), res, 1); +} + +unsigned int BridgeClass::get(const char *key, uint8_t *value, unsigned int maxlen) { + uint8_t cmd[] = {'d'}; + unsigned int l = transfer(cmd, 1, (uint8_t *)key, strlen(key), value, maxlen); + if (l < maxlen) + value[l] = 0; // Zero-terminate string + return l; +} + +#if defined(ARDUINO_ARCH_AVR) +// AVR use an optimized implementation of CRC +#include +#else +// Generic implementation for non-AVR architectures +uint16_t _crc_ccitt_update(uint16_t crc, uint8_t data) +{ + data ^= crc & 0xff; + data ^= data << 4; + return ((((uint16_t)data << 8) | ((crc >> 8) & 0xff)) ^ + (uint8_t)(data >> 4) ^ + ((uint16_t)data << 3)); +} +#endif + +void BridgeClass::crcUpdate(uint8_t c) { + CRC = _crc_ccitt_update(CRC, c); +} + +void BridgeClass::crcReset() { + CRC = 0xFFFF; +} + +void BridgeClass::crcWrite() { + stream.write((char)(CRC >> 8)); + stream.write((char)(CRC & 0xFF)); +} + +bool BridgeClass::crcCheck(uint16_t _CRC) { + return CRC == _CRC; +} + +uint16_t BridgeClass::transfer(const uint8_t *buff1, uint16_t len1, + const uint8_t *buff2, uint16_t len2, + const uint8_t *buff3, uint16_t len3, + uint8_t *rxbuff, uint16_t rxlen) +{ + uint16_t len = len1 + len2 + len3; + uint8_t retries = 0; + for ( ; retries < max_retries; retries++, delay(100), dropAll() /* Delay for retransmission */) { + // Send packet + crcReset(); + stream.write((char)0xFF); // Start of packet (0xFF) + crcUpdate(0xFF); + stream.write((char)index); // Message index + crcUpdate(index); + stream.write((char)((len >> 8) & 0xFF)); // Message length (hi) + crcUpdate((len >> 8) & 0xFF); + stream.write((char)(len & 0xFF)); // Message length (lo) + crcUpdate(len & 0xFF); + for (uint16_t i = 0; i < len1; i++) { // Payload + stream.write((char)buff1[i]); + crcUpdate(buff1[i]); + } + for (uint16_t i = 0; i < len2; i++) { // Payload + stream.write((char)buff2[i]); + crcUpdate(buff2[i]); + } + for (uint16_t i = 0; i < len3; i++) { // Payload + stream.write((char)buff3[i]); + crcUpdate(buff3[i]); + } + crcWrite(); // CRC + + // Wait for ACK in 200ms + if (timedRead(200) != 0xFF) + continue; + crcReset(); + crcUpdate(0xFF); + + // Check packet index + if (timedRead(5) != index) + continue; + crcUpdate(index); + + // Recv len + int lh = timedRead(10); + if (lh < 0) + continue; + crcUpdate(lh); + int ll = timedRead(10); + if (ll < 0) + continue; + crcUpdate(ll); + uint16_t l = lh; + l <<= 8; + l += ll; + + // Recv data + for (uint16_t i = 0; i < l; i++) { + // Cut received data if rxbuffer is too small + if (i >= rxlen) + break; + int c = timedRead(5); + if (c < 0) + continue; + rxbuff[i] = c; + crcUpdate(c); + } + + // Check CRC + int crc_hi = timedRead(5); + if (crc_hi < 0) + continue; + int crc_lo = timedRead(5); + if (crc_lo < 0) + continue; + if (!crcCheck((crc_hi << 8) + crc_lo)) + continue; + + // Increase index + index++; + + // Return bytes received + if (l > rxlen) + return rxlen; + return l; + } + + // Max retries exceeded + return TRANSFER_TIMEOUT; +} + +int BridgeClass::timedRead(unsigned int timeout) { + int c; + unsigned long _startMillis = millis(); + do { + c = stream.read(); + if (c >= 0) return c; + } while (millis() - _startMillis < timeout); + return -1; // -1 indicates timeout +} + +void BridgeClass::dropAll() { + while (stream.available() > 0) { + stream.read(); + } +} + +#if defined(ARDUINO_ARCH_SAM) +#include +#endif + +#if defined(ARDUINO_ARCH_SAM) +void checkForRemoteSketchUpdate(uint8_t pin) { + // The host force pin LOW to signal that a new sketch is coming + pinMode(pin, INPUT_PULLUP); + delay(50); + if (digitalRead(pin) == LOW) { + initiateReset(1); + while (true) + ; // Wait for reset to SAM-BA + } + + // Restore in standard state + pinMode(pin, INPUT); +} +#else +void checkForRemoteSketchUpdate(uint8_t /* pin */) { + // Empty, bootloader is enough. +} +#endif + +// Bridge instance +#if defined(SERIAL_PORT_LINUXBRIDGE) +SerialBridgeClass Bridge(SERIAL_PORT_LINUXBRIDGE); +#elif defined(SERIAL_PORT_HARDWARE) +SerialBridgeClass Bridge(SERIAL_PORT_HARDWARE); +#elif defined(SERIAL_PORT_HARDWARE_OPEN) +SerialBridgeClass Bridge(SERIAL_PORT_HARDWARE_OPEN); +#elif defined(__AVR_ATmega32U4__) // Legacy fallback +// Leonardo variants (where HardwareSerial is Serial1) +SerialBridgeClass Bridge(Serial1); +#else +SerialBridgeClass Bridge(Serial); +#endif + diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/src/Bridge.h b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/Bridge.h new file mode 100644 index 000000000..519c096bf --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/Bridge.h @@ -0,0 +1,131 @@ +/* + Copyright (c) 2013 Arduino LLC. 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 BRIDGE_H_ +#define BRIDGE_H_ + +#ifndef BRIDGE_BAUDRATE +#define BRIDGE_BAUDRATE 250000 +#endif + +#include +#include + +class BridgeClass { + public: + BridgeClass(Stream &_stream); + void begin(); + void end(); + + // Methods to handle key/value datastore + void put(const char *key, const char *value); + void put(const String &key, const String &value) + { + put(key.c_str(), value.c_str()); + } + unsigned int get(const char *key, uint8_t *buff, unsigned int size); + unsigned int get(const char *key, char *value, unsigned int maxlen) + { + return get(key, reinterpret_cast(value), maxlen); + } + + // Trasnfer a frame (with error correction and response) + uint16_t transfer(const uint8_t *buff1, uint16_t len1, + const uint8_t *buff2, uint16_t len2, + const uint8_t *buff3, uint16_t len3, + uint8_t *rxbuff, uint16_t rxlen); + // multiple inline versions of the same function to allow efficient frame concatenation + uint16_t transfer(const uint8_t *buff1, uint16_t len1) + { + return transfer(buff1, len1, NULL, 0); + } + uint16_t transfer(const uint8_t *buff1, uint16_t len1, + uint8_t *rxbuff, uint16_t rxlen) + { + return transfer(buff1, len1, NULL, 0, rxbuff, rxlen); + } + uint16_t transfer(const uint8_t *buff1, uint16_t len1, + const uint8_t *buff2, uint16_t len2, + uint8_t *rxbuff, uint16_t rxlen) + { + return transfer(buff1, len1, buff2, len2, NULL, 0, rxbuff, rxlen); + } + + uint16_t getBridgeVersion() + { + return bridgeVersion; + } + + static const uint16_t TRANSFER_TIMEOUT = 0xFFFF; + + private: + uint8_t index; + int timedRead(unsigned int timeout); + void dropAll(); + uint16_t bridgeVersion; + + private: + void crcUpdate(uint8_t c); + void crcReset(); + void crcWrite(); + bool crcCheck(uint16_t _CRC); + uint16_t CRC; + + private: + static const char CTRL_C = 3; + Stream &stream; + bool started; + uint8_t max_retries; +}; + +// This subclass uses a serial port Stream +class SerialBridgeClass : public BridgeClass { + public: + SerialBridgeClass(HardwareSerial &_serial) + : BridgeClass(_serial), serial(_serial) { + // Empty + } + + void begin(unsigned long baudrate = BRIDGE_BAUDRATE) { + serial.begin(baudrate); + BridgeClass::begin(); + } + + void end(unsigned long baudrate = BRIDGE_BAUDRATE) { + serial.begin(baudrate); + BridgeClass::end(); + } + + private: + HardwareSerial &serial; +}; + +extern SerialBridgeClass Bridge; + +// Some microcrontrollers don't start the bootloader after a reset. +// This function is intended to let the microcontroller erase its +// flash after checking a specific signal coming from the external +// device without the need to press the erase button on the board. +// The purpose is to enable a software update that does not require +// a manual interaction with the board. +extern void checkForRemoteSketchUpdate(uint8_t pin = 7); + +#endif /* BRIDGE_H_ */ + +#include +#include diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeClient.cpp b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeClient.cpp new file mode 100644 index 000000000..a342abcf2 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeClient.cpp @@ -0,0 +1,207 @@ +/* + Copyright (c) 2013 Arduino LLC. 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 + +BridgeClient::BridgeClient(uint8_t _h, BridgeClass &_b) : + bridge(_b), handle(_h), opened(true), buffered(0) { +} + +BridgeClient::BridgeClient(BridgeClass &_b) : + bridge(_b), handle(0), opened(false), buffered(0) { +} + +BridgeClient::~BridgeClient() { +} + +BridgeClient& BridgeClient::operator=(const BridgeClient &_x) { + opened = _x.opened; + handle = _x.handle; + return *this; +} + +void BridgeClient::stop() { + if (opened) { + uint8_t cmd[] = {'j', handle}; + bridge.transfer(cmd, 2); + } + opened = false; + buffered = 0; + readPos = 0; +} + +void BridgeClient::doBuffer() { + // If there are already char in buffer exit + if (buffered > 0) + return; + + // Try to buffer up to 32 characters + readPos = 0; + uint8_t cmd[] = {'K', handle, sizeof(buffer)}; + buffered = bridge.transfer(cmd, 3, buffer, sizeof(buffer)); +} + +int BridgeClient::available() { + // Look if there is new data available + doBuffer(); + return buffered; +} + +int BridgeClient::read() { + doBuffer(); + if (buffered == 0) + return -1; // no chars available + else { + buffered--; + return buffer[readPos++]; + } +} + +int BridgeClient::read(uint8_t *buff, size_t size) { + size_t readed = 0; + do { + if (buffered == 0) { + doBuffer(); + if (buffered == 0) + return readed; + } + buff[readed++] = buffer[readPos++]; + buffered--; + } while (readed < size); + return readed; +} + +int BridgeClient::peek() { + doBuffer(); + if (buffered == 0) + return -1; // no chars available + else + return buffer[readPos]; +} + +size_t BridgeClient::write(uint8_t c) { + if (!opened) + return 0; + uint8_t cmd[] = {'l', handle, c}; + bridge.transfer(cmd, 3); + return 1; +} + +size_t BridgeClient::write(const uint8_t *buf, size_t size) { + if (!opened) + return 0; + uint8_t cmd[] = {'l', handle}; + bridge.transfer(cmd, 2, buf, size, NULL, 0); + return size; +} + +void BridgeClient::flush() { +} + +uint8_t BridgeClient::connected() { + if (!opened) + return false; + // Client is "connected" if it has unread bytes + if (available()) + return true; + + uint8_t cmd[] = {'L', handle}; + uint8_t res[1]; + bridge.transfer(cmd, 2, res, 1); + return (res[0] == 1); +} + +int BridgeClient::connect(IPAddress ip, uint16_t port) { + String address; + address.reserve(18); + address += ip[0]; + address += '.'; + address += ip[1]; + address += '.'; + address += ip[2]; + address += '.'; + address += ip[3]; + return connect(address.c_str(), port); +} + +int BridgeClient::connect(const char *host, uint16_t port) { + uint8_t tmp[] = { + 'C', + static_cast(port >> 8), + static_cast(port) + }; + uint8_t res[1]; + int l = bridge.transfer(tmp, 3, (const uint8_t *)host, strlen(host), res, 1); + if (l == 0) + return 0; + handle = res[0]; + + // wait for connection + uint8_t tmp2[] = { 'c', handle }; + uint8_t res2[1]; + while (true) { + bridge.transfer(tmp2, 2, res2, 1); + if (res2[0] == 0) + break; + delay(1); + } + opened = true; + + // check for successful connection + if (connected()) + return 1; + + stop(); + handle = 0; + return 0; +} + +int BridgeClient::connectSSL(const char *host, uint16_t port) { + if (bridge.getBridgeVersion() < 161) + return -1; + + uint8_t tmp[] = { + 'Z', + static_cast(port >> 8), + static_cast(port) + }; + uint8_t res[1]; + int l = bridge.transfer(tmp, 3, (const uint8_t *)host, strlen(host), res, 1); + if (l == 0) + return 0; + handle = res[0]; + + // wait for connection + uint8_t tmp2[] = { 'c', handle }; + uint8_t res2[1]; + while (true) { + bridge.transfer(tmp2, 2, res2, 1); + if (res2[0] == 0) + break; + delay(1); + } + opened = true; + + // check for successful connection + if (connected()) + return 1; + + stop(); + handle = 0; + return 0; +} \ No newline at end of file diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeClient.h b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeClient.h new file mode 100644 index 000000000..a55ebb712 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeClient.h @@ -0,0 +1,71 @@ +/* + Copyright (c) 2013 Arduino LLC. 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 _BRIDGE_CLIENT_H_ +#define _BRIDGE_CLIENT_H_ + +#include +#include + +class BridgeClient : public Client { + public: + // Constructor with a user provided BridgeClass instance + BridgeClient(uint8_t _h, BridgeClass &_b = Bridge); + BridgeClient(BridgeClass &_b = Bridge); + ~BridgeClient(); + + // Stream methods + // (read message) + virtual int available(); + virtual int read(); + virtual int read(uint8_t *buf, size_t size); + virtual int peek(); + // (write response) + virtual size_t write(uint8_t); + virtual size_t write(const uint8_t *buf, size_t size); + virtual void flush(); + // TODO: add optimized function for block write + + virtual operator bool () { + return opened; + } + + virtual BridgeClient& operator=(const BridgeClient &_x); + + virtual void stop(); + virtual uint8_t connected(); + + virtual int connect(IPAddress ip, uint16_t port); + virtual int connect(const char *host, uint16_t port); + int connectSSL(const char* host, uint16_t port); + + private: + BridgeClass &bridge; + uint8_t handle; + boolean opened; + + private: + void doBuffer(); + uint8_t buffered; + uint8_t readPos; + static const int BUFFER_SIZE = 64; + uint8_t buffer[BUFFER_SIZE]; + +}; + +#endif // _BRIDGE_CLIENT_H_ diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeSSLClient.cpp b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeSSLClient.cpp new file mode 100644 index 000000000..dd8d34b0a --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeSSLClient.cpp @@ -0,0 +1,36 @@ +/* + Copyright (c) 2016 Arduino LLC. 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 + +BridgeSSLClient::BridgeSSLClient(uint8_t _h, BridgeClass &_b) : + BridgeClient(_h, _b) +{ +} + +BridgeSSLClient::BridgeSSLClient(BridgeClass &_b): + BridgeClient(_b) +{ +} + +BridgeSSLClient::~BridgeSSLClient() { +} + +int BridgeSSLClient::connect(const char *host, uint16_t port) { + return BridgeClient::connectSSL(host, port); +} \ No newline at end of file diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeSSLClient.h b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeSSLClient.h new file mode 100644 index 000000000..2f09afbeb --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeSSLClient.h @@ -0,0 +1,36 @@ +/* + Copyright (c) 2016 Arduino LLC. 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 _BRIDGE_SSL_CLIENT_H_ +#define _BRIDGE_SSL_CLIENT_H_ + +#include +#include +#include + +class BridgeSSLClient : public BridgeClient { + public: + // Constructor with a user provided BridgeClass instance + BridgeSSLClient(uint8_t _h, BridgeClass &_b = Bridge); + BridgeSSLClient(BridgeClass &_b = Bridge); + ~BridgeSSLClient(); + + virtual int connect(const char* host, uint16_t port); +}; + +#endif // _BRIDGE_SSL_CLIENT_H_ diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeServer.cpp b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeServer.cpp new file mode 100644 index 000000000..a7aa9b0ae --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeServer.cpp @@ -0,0 +1,54 @@ +/* + Copyright (c) 2013 Arduino LLC. 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 + +BridgeServer::BridgeServer(uint16_t _p, BridgeClass &_b) : + bridge(_b), port(_p), listening(false), useLocalhost(false) { +} + +void BridgeServer::begin() { + uint8_t tmp[] = { + 'N', + static_cast(port >> 8), + static_cast(port) + }; + uint8_t res[1]; + String address = F("127.0.0.1"); + if (!useLocalhost) + address = F("0.0.0.0"); + bridge.transfer(tmp, 3, (const uint8_t *)address.c_str(), address.length(), res, 1); + listening = (res[0] == 1); +} + +BridgeClient BridgeServer::accept() { + uint8_t cmd[] = {'k'}; + uint8_t res[1]; + unsigned int l = bridge.transfer(cmd, 1, res, 1); + if (l == 0) + return BridgeClient(); + return BridgeClient(res[0]); +} + +size_t BridgeServer::write(uint8_t c) { + uint8_t cmd[] = { 'b', c }; + bridge.transfer(cmd, 2); + return 1; +} + diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeServer.h b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeServer.h new file mode 100644 index 000000000..676a9729b --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeServer.h @@ -0,0 +1,51 @@ +/* + Copyright (c) 2013 Arduino LLC. 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 _BRIDGE_SERVER_H_ +#define _BRIDGE_SERVER_H_ + +#include +#include + +class BridgeClient; + +class BridgeServer : public Server { + public: + // Constructor with a user provided BridgeClass instance + BridgeServer(uint16_t port = 5555, BridgeClass &_b = Bridge); + + void begin(); + BridgeClient accept(); + + virtual size_t write(uint8_t c); + + void listenOnLocalhost() { + useLocalhost = true; + } + void noListenOnLocalhost() { + useLocalhost = false; + } + + private: + BridgeClass &bridge; + uint16_t port; + bool listening; + bool useLocalhost; +}; + +#endif // _BRIDGE_SERVER_H_ diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeUdp.cpp b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeUdp.cpp new file mode 100644 index 000000000..ae630e3ab --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeUdp.cpp @@ -0,0 +1,198 @@ +/* + Copyright (c) 2015 Arduino LLC. 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 "BridgeUdp.h" + +BridgeUDP::BridgeUDP(BridgeClass &_b) : + bridge(_b), opened(false), avail(0), buffered(0), readPos(0) { +} + +/* Start BridgeUDP socket, listening at local port PORT */ +uint8_t BridgeUDP::begin(uint16_t port) { + if (opened) + return 0; + uint8_t cmd[] = {'e', (uint8_t)((port >> 8) & 0xFF), (uint8_t)(port & 0xFF)}; + uint8_t res[2]; + bridge.transfer(cmd, 3, res, 2); + if (res[1] == 1) // Error... + return 0; + handle = res[0]; + opened = true; + return 1; +} + +/* Release any resources being used by this BridgeUDP instance */ +void BridgeUDP::stop() +{ + if (!opened) + return; + uint8_t cmd[] = {'q', handle}; + bridge.transfer(cmd, 2); + opened = false; +} + +int BridgeUDP::beginPacket(const char *host, uint16_t port) +{ + if (!opened) + return 0; + uint8_t cmd[] = {'E', handle, (uint8_t)((port >> 8) & 0xFF), (uint8_t)(port & 0xFF)}; + uint8_t res[1]; + bridge.transfer(cmd, 4, (const uint8_t *)host, strlen(host), res, 1); + return res[0]; // 1=Success, 0=Error +} + +int BridgeUDP::beginBroadcastPacket(uint16_t port) +{ + if (!opened) + return 0; + uint8_t cmd[] = {'v', handle, (uint8_t)((port >> 8) & 0xFF), (uint8_t)(port & 0xFF)}; + uint8_t res[1]; + bridge.transfer(cmd, 4, res, 1); + return res[0]; // 1=Success, 0=Error +} + +int BridgeUDP::beginPacket(IPAddress ip, uint16_t port) +{ + if (!opened) + return 0; + String address; + address.reserve(18); + address += ip[0]; + address += '.'; + address += ip[1]; + address += '.'; + address += ip[2]; + address += '.'; + address += ip[3]; + return beginPacket(address.c_str(), port); +} + +int BridgeUDP::endPacket() +{ + if (!opened) + return 0; + uint8_t cmd[] = {'H', handle}; + uint8_t res[1]; + bridge.transfer(cmd, 2, res, 1); + return res[0]; // 1=Success, 0=Error +} + +size_t BridgeUDP::write(const uint8_t *buffer, size_t size) +{ + if (!opened) + return 0; + uint8_t cmd[] = {'h', handle}; + uint8_t res[1]; + bridge.transfer(cmd, 2, buffer, size, res, 1); + return res[0]; // 1=Success, 0=Error +} + +int BridgeUDP::parsePacket() +{ + if (!opened) + return 0; + buffered = 0; + readPos = 0; + uint8_t cmd[] = {'Q', handle}; + uint8_t res[3]; + bridge.transfer(cmd, 2, res, 3); + if (res[0] == 0) { + // There aren't any packets available + return 0; + } + avail = (res[1] << 8) + res[2]; + return 1; +} + +void BridgeUDP::doBuffer() { + // If there are already char in buffer exit + if (buffered > 0) + return; + if (avail == 0) + return; + + // Try to buffer up to 32 characters + readPos = 0; + uint8_t cmd[] = {'u', handle, sizeof(buffer)}; + buffered = bridge.transfer(cmd, 3, buffer, sizeof(buffer)); +} + +int BridgeUDP::read() +{ + if (!opened) + return -1; + doBuffer(); + if (buffered == 0) { + return -1; // no chars available + } + buffered--; + avail--; + return buffer[readPos++]; +} + +int BridgeUDP::read(unsigned char* buff, size_t size) +{ + if (!opened) + return -1; + size_t readed = 0; + do { + if (buffered == 0) { + doBuffer(); + if (buffered == 0) + return readed; + } + buff[readed++] = buffer[readPos++]; + buffered--; + avail--; + } while (readed < size); + return readed; +} + +int BridgeUDP::peek() +{ + if (!opened) + return -1; + doBuffer(); + if (buffered == 0) + return -1; // no chars available + return buffer[readPos]; +} + +IPAddress BridgeUDP::remoteIP() +{ + if (!opened) + return -1; + uint8_t cmd[] = {'T', handle}; + uint8_t res[7]; + bridge.transfer(cmd, 2, res, 7); + if (res[0] == 0) + return IPAddress(0,0,0,0); + return IPAddress(res[1], res[2], res[3], res[4]); +} + +uint16_t BridgeUDP::remotePort() +{ + if (!opened) + return -1; + uint8_t cmd[] = {'T', handle}; + uint8_t res[7]; + bridge.transfer(cmd, 2, res, 7); + if (res[0] == 0) + return 0; + return (res[5] << 8) + res[6]; +} diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeUdp.h b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeUdp.h new file mode 100644 index 000000000..73cec54ea --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/BridgeUdp.h @@ -0,0 +1,65 @@ +/* + Copyright (c) 2015 Arduino LLC. 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 +*/ + +#pragma once + +#include +#include "Bridge.h" + +class BridgeUDP : public UDP { + + public: + BridgeUDP(BridgeClass &_b = Bridge); + virtual uint8_t begin(uint16_t); + virtual void stop(); + + virtual int beginPacket(IPAddress ip, uint16_t port); + virtual int beginPacket(const char *host, uint16_t port); + virtual int beginBroadcastPacket(uint16_t port); + virtual int endPacket(); + virtual size_t write(uint8_t d) { return write(&d, 1); } + virtual size_t write(const uint8_t *buffer, size_t size); + + using Print::write; + + virtual int parsePacket(); + /* return number of bytes available in the current packet, + will return zero if parsePacket hasn't been called yet */ + virtual int available() { return avail; } + virtual int read(); + virtual int read(unsigned char* buffer, size_t len); + virtual int read(char* buffer, size_t len) { return read((unsigned char*)buffer, len); }; + virtual int peek(); + virtual void flush() { avail = 0; } + + virtual IPAddress remoteIP(); + virtual uint16_t remotePort(); + + private: + BridgeClass &bridge; + uint8_t handle; + boolean opened; + + private: + void doBuffer(); + uint16_t avail; + uint8_t buffered; + uint8_t readPos; + static const int BUFFER_SIZE = 64; + uint8_t buffer[BUFFER_SIZE]; +}; diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/src/Console.cpp b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/Console.cpp new file mode 100644 index 000000000..7e8323d45 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/Console.cpp @@ -0,0 +1,150 @@ +/* + Copyright (c) 2013 Arduino LLC. 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 + +// Default constructor uses global Bridge instance +ConsoleClass::ConsoleClass() : + bridge(Bridge), inBuffered(0), inReadPos(0), inBuffer(NULL), + autoFlush(true) +{ + // Empty +} + +// Constructor with a user provided BridgeClass instance +ConsoleClass::ConsoleClass(BridgeClass &_b) : + bridge(_b), inBuffered(0), inReadPos(0), inBuffer(NULL), + autoFlush(true) +{ + // Empty +} + +ConsoleClass::~ConsoleClass() { + end(); +} + +size_t ConsoleClass::write(uint8_t c) { + if (autoFlush) { + uint8_t tmp[] = { 'P', c }; + bridge.transfer(tmp, 2); + } else { + outBuffer[outBuffered++] = c; + if (outBuffered == outBufferSize) + flush(); + } + return 1; +} + +size_t ConsoleClass::write(const uint8_t *buff, size_t size) { + if (autoFlush) { + uint8_t tmp[] = { 'P' }; + bridge.transfer(tmp, 1, buff, size, NULL, 0); + } else { + size_t sent = size; + while (sent > 0) { + outBuffer[outBuffered++] = *buff++; + sent--; + if (outBuffered == outBufferSize) + flush(); + } + } + return size; +} + +void ConsoleClass::flush() { + if (autoFlush) + return; + + bridge.transfer(outBuffer, outBuffered); + outBuffered = 1; +} + +void ConsoleClass::noBuffer() { + if (autoFlush) + return; + delete[] outBuffer; + autoFlush = true; +} + +void ConsoleClass::buffer(uint8_t size) { + noBuffer(); + if (size == 0) + return; + outBuffer = new uint8_t[size + 1]; + outBuffer[0] = 'P'; // WRITE tag + outBufferSize = size + 1; + outBuffered = 1; + autoFlush = false; +} + +bool ConsoleClass::connected() { + uint8_t tmp = 'a'; + bridge.transfer(&tmp, 1, &tmp, 1); + return tmp == 1; +} + +int ConsoleClass::available() { + // Look if there is new data available + doBuffer(); + return inBuffered; +} + +int ConsoleClass::read() { + doBuffer(); + if (inBuffered == 0) + return -1; // no chars available + else { + inBuffered--; + return inBuffer[inReadPos++]; + } +} + +int ConsoleClass::peek() { + doBuffer(); + if (inBuffered == 0) + return -1; // no chars available + else + return inBuffer[inReadPos]; +} + +void ConsoleClass::doBuffer() { + // If there are already char in buffer exit + if (inBuffered > 0) + return; + + // Try to buffer up to 32 characters + inReadPos = 0; + uint8_t tmp[] = { 'p', BUFFER_SIZE }; + inBuffered = bridge.transfer(tmp, 2, inBuffer, BUFFER_SIZE); +} + +void ConsoleClass::begin() { + bridge.begin(); + end(); + inBuffer = new uint8_t[BUFFER_SIZE]; +} + +void ConsoleClass::end() { + noBuffer(); + if (inBuffer) { + delete[] inBuffer; + inBuffer = NULL; + } +} + +ConsoleClass Console; diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/src/Console.h b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/Console.h new file mode 100644 index 000000000..ca05b08cf --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/Console.h @@ -0,0 +1,71 @@ +/* + Copyright (c) 2013 Arduino LLC. 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 CONSOLE_H_ +#define CONSOLE_H_ + +#include + +class ConsoleClass : public Stream { + public: + // Default constructor uses global Bridge instance + ConsoleClass(); + // Constructor with a user provided BridgeClass instance + ConsoleClass(BridgeClass &_b); + ~ConsoleClass(); + + void begin(); + void end(); + + void buffer(uint8_t size); + void noBuffer(); + + bool connected(); + + // Stream methods + // (read from console socket) + int available(); + int read(); + int peek(); + // (write to console socket) + size_t write(uint8_t); + size_t write(const uint8_t *buffer, size_t size); + void flush(); + + operator bool () { + return connected(); + } + + private: + BridgeClass &bridge; + + void doBuffer(); + uint8_t inBuffered; + uint8_t inReadPos; + static const int BUFFER_SIZE = 32; + uint8_t *inBuffer; + + bool autoFlush; + uint8_t outBuffered; + uint8_t outBufferSize; + uint8_t *outBuffer; +}; + +extern ConsoleClass Console; + +#endif diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/src/FileIO.cpp b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/FileIO.cpp new file mode 100644 index 000000000..e24a56796 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/FileIO.cpp @@ -0,0 +1,283 @@ +/* + Copyright (c) 2013 Arduino LLC. 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 + +namespace BridgeLib { + +File::File(BridgeClass &b) : bridge(b), mode(255) { + // Empty +} + +File::File(const char *_filename, uint8_t _mode, BridgeClass &b) : bridge(b), mode(_mode) { + filename = _filename; + uint8_t modes[] = {'r', 'w', 'a'}; + uint8_t cmd[] = {'F', modes[mode]}; + uint8_t res[2]; + dirPosition = 1; + bridge.transfer(cmd, 2, (uint8_t*)filename.c_str(), filename.length(), res, 2); + if (res[0] != 0) { // res[0] contains error code + mode = 255; // In case of error keep the file closed + return; + } + handle = res[1]; + buffered = 0; +} + +File::operator bool() { + return (mode != 255); +} + +File::~File() { + close(); +} + +size_t File::write(uint8_t c) { + return write(&c, 1); +} + +size_t File::write(const uint8_t *buf, size_t size) { + if (mode == 255) + return -1; + uint8_t cmd[] = {'g', handle}; + uint8_t res[1]; + bridge.transfer(cmd, 2, buf, size, res, 1); + if (res[0] != 0) // res[0] contains error code + return -res[0]; + return size; +} + +int File::read() { + doBuffer(); + if (buffered == 0) + return -1; // no chars available + else { + buffered--; + return buffer[readPos++]; + } +} + +int File::peek() { + doBuffer(); + if (buffered == 0) + return -1; // no chars available + else + return buffer[readPos]; +} + +boolean File::seek(uint32_t position) { + uint8_t cmd[] = { + 's', + handle, + static_cast(position >> 24), + static_cast(position >> 16), + static_cast(position >> 8), + static_cast(position) + }; + uint8_t res[1]; + bridge.transfer(cmd, 6, res, 1); + if (res[0] == 0) { + // If seek succeed then flush buffers + buffered = 0; + return true; + } + return false; +} + +uint32_t File::position() { + uint8_t cmd[] = {'S', handle}; + uint8_t res[5]; + bridge.transfer(cmd, 2, res, 5); + //err = res[0]; // res[0] contains error code + uint32_t pos; + pos = static_cast(res[1]) << 24; + pos += static_cast(res[2]) << 16; + pos += static_cast(res[3]) << 8; + pos += static_cast(res[4]); + return pos - buffered; +} + +void File::doBuffer() { + // If there are already char in buffer exit + if (buffered > 0) + return; + + // Try to buffer up to BUFFER_SIZE characters + readPos = 0; + uint8_t cmd[] = {'G', handle, BUFFER_SIZE - 1}; + uint16_t readed = bridge.transfer(cmd, 3, buffer, BUFFER_SIZE); + //err = buff[0]; // First byte is error code + if (readed == BridgeClass::TRANSFER_TIMEOUT || readed == 0) { + // transfer failed to retrieve any data + buffered = 0; + } else { + // transfer retrieved at least one byte of data so skip the error code character + readPos++; + buffered = readed - 1; + } +} + +int File::available() { + // Look if there is new data available + doBuffer(); + return buffered; +} + +void File::flush() { +} + +int File::read(void *buff, uint16_t nbyte) { + uint16_t n = 0; + uint8_t *p = reinterpret_cast(buff); + while (n < nbyte) { + if (buffered == 0) { + doBuffer(); + if (buffered == 0) + break; + } + *p++ = buffer[readPos++]; + buffered--; + n++; + } + return n; +} + +uint32_t File::size() { + if (bridge.getBridgeVersion() < 101) + return 0; + uint8_t cmd[] = {'t', handle}; + uint8_t buff[5]; + bridge.transfer(cmd, 2, buff, 5); + //err = res[0]; // First byte is error code + uint32_t res; + res = ((uint32_t)buff[1]) << 24; + res |= ((uint32_t)buff[2]) << 16; + res |= ((uint32_t)buff[3]) << 8; + res |= ((uint32_t)buff[4]); + return res; +} + +void File::close() { + if (mode == 255) + return; + uint8_t cmd[] = {'f', handle}; + uint8_t ret[1]; + bridge.transfer(cmd, 2, ret, 1); + mode = 255; +} + +const char *File::name() { + return filename.c_str(); +} + + +boolean File::isDirectory() { + uint8_t res[1]; + uint8_t cmd[] = {'i'}; + if (mode != 255) + return 0; + + bridge.transfer(cmd, 1, (uint8_t *)filename.c_str(), filename.length(), res, 1); + return res[0]; +} + + +File File::openNextFile(uint8_t mode) { + Process awk; + char tmp; + String command; + String filepath; + if (dirPosition == 0xFFFF) return File(); + + command = "ls "; + command += filename; + command += " | awk 'NR=="; + command += dirPosition; + command += "'"; + + awk.runShellCommand(command); + + while (awk.running()); + + command = ""; + + while (awk.available()) { + tmp = awk.read(); + if (tmp != '\n') command += tmp; + } + if (command.length() == 0) + return File(); + dirPosition++; + filepath = filename + "/" + command; + return File(filepath.c_str(), mode); + +} + +void File::rewindDirectory(void) { + dirPosition = 1; +} + + + + + + +boolean FileSystemClass::begin() { + return true; +} + +File FileSystemClass::open(const char *filename, uint8_t mode) { + return File(filename, mode); +} + +boolean FileSystemClass::exists(const char *filepath) { + Process ls; + ls.begin("ls"); + ls.addParameter(filepath); + int res = ls.run(); + return (res == 0); +} + +boolean FileSystemClass::mkdir(const char *filepath) { + Process mk; + mk.begin("mkdir"); + mk.addParameter("-p"); + mk.addParameter(filepath); + int res = mk.run(); + return (res == 0); +} + +boolean FileSystemClass::remove(const char *filepath) { + Process rm; + rm.begin("rm"); + rm.addParameter(filepath); + int res = rm.run(); + return (res == 0); +} + +boolean FileSystemClass::rmdir(const char *filepath) { + Process rm; + rm.begin("rmdir"); + rm.addParameter(filepath); + int res = rm.run(); + return (res == 0); +} + +FileSystemClass FileSystem; + +} diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/src/FileIO.h b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/FileIO.h new file mode 100644 index 000000000..c5a8e9eac --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/FileIO.h @@ -0,0 +1,120 @@ +/* + Copyright (c) 2013 Arduino LLC. 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 __FILEIO_H__ +#define __FILEIO_H__ + +#include + +#define FILE_READ 0 +#define FILE_WRITE 1 +#define FILE_APPEND 2 + +namespace BridgeLib { + +class File : public Stream { + + public: + File(BridgeClass &b = Bridge); + File(const char *_filename, uint8_t _mode, BridgeClass &b = Bridge); + ~File(); + + virtual size_t write(uint8_t); + virtual size_t write(const uint8_t *buf, size_t size); + virtual int read(); + virtual int peek(); + virtual int available(); + virtual void flush(); + int read(void *buf, uint16_t nbyte); + boolean seek(uint32_t pos); + uint32_t position(); + uint32_t size(); + void close(); + operator bool(); + const char * name(); + boolean isDirectory(); + File openNextFile(uint8_t mode = FILE_READ); + void rewindDirectory(void); + + //using Print::write; + + private: + void doBuffer(); + uint8_t buffered; + uint8_t readPos; + uint16_t dirPosition; + static const int BUFFER_SIZE = 64; + uint8_t buffer[BUFFER_SIZE]; + + + private: + BridgeClass &bridge; + String filename; + uint8_t mode; + uint8_t handle; + +}; + +class FileSystemClass { + public: + FileSystemClass() : bridge(Bridge) { } + FileSystemClass(BridgeClass &_b) : bridge(_b) { } + + boolean begin(); + + // Open the specified file/directory with the supplied mode (e.g. read or + // write, etc). Returns a File object for interacting with the file. + // Note that currently only one file can be open at a time. + File open(const char *filename, uint8_t mode = FILE_READ); + + // Methods to determine if the requested file path exists. + boolean exists(const char *filepath); + + // Create the requested directory hierarchy--if intermediate directories + // do not exist they will be created. + boolean mkdir(const char *filepath); + + // Delete the file. + boolean remove(const char *filepath); + + boolean rmdir(const char *filepath); + + private: + friend class File; + + BridgeClass &bridge; +}; + +extern FileSystemClass FileSystem; + +}; + +// We enclose File and FileSystem classes in namespace BridgeLib to avoid +// conflicts with legacy SD library. + +// This ensure compatibility with older sketches that uses only Bridge lib +// (the user can still use File instead of BridgeFile) +using namespace BridgeLib; + +// This allows sketches to use BridgeLib::File together with SD library +// (you must use BridgeFile instead of File when needed to disambiguate) +typedef BridgeLib::File BridgeFile; +typedef BridgeLib::FileSystemClass BridgeFileSystemClass; +#define BridgeFileSystem BridgeLib::FileSystem + +#endif diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/src/HttpClient.cpp b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/HttpClient.cpp new file mode 100644 index 000000000..ee1629cc3 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/HttpClient.cpp @@ -0,0 +1,204 @@ +/* + Copyright (c) 2013-2014 Arduino LLC. 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 "HttpClient.h" + +HttpClient::HttpClient() : + insecure(false) { + // Empty +} + +unsigned int HttpClient::get(String &url) { + begin("curl"); + if (insecure) { + addParameter("-k"); + } + addHeader(); + addParameter(url); + return run(); +} + +unsigned int HttpClient::get(const char *url) { + begin("curl"); + if (insecure) { + addParameter("-k"); + } + addHeader(); + addParameter(url); + return run(); +} + +void HttpClient::getAsynchronously(String &url) { + begin("curl"); + if (insecure) { + addParameter("-k"); + } + addHeader(); + addParameter(url); + runAsynchronously(); +} + +void HttpClient::getAsynchronously(const char *url) { + begin("curl"); + if (insecure) { + addParameter("-k"); + } + addHeader(); + addParameter(url); + runAsynchronously(); +} + +unsigned int HttpClient::post(String &url, String &data) { + return post(url.c_str(), data.c_str()); +} + +unsigned int HttpClient::post(const char *url, const char *data) { + begin("curl"); + if (insecure) { + addParameter("-k"); + } + addParameter("--request"); + addParameter("POST"); + addParameter("--data"); + addParameter(data); + addHeader(); + addParameter(url); + return run(); +} + +void HttpClient::postAsynchronously(String &url, String &data) { + postAsynchronously(url.c_str(), data.c_str()); +} + +void HttpClient::postAsynchronously(const char *url, const char *data) { + begin("curl"); + if (insecure) { + addParameter("-k"); + } + addParameter("--request"); + addParameter("POST"); + addParameter("--data"); + addParameter(data); + addHeader(); + addParameter(url); + runAsynchronously(); +} + +unsigned int HttpClient::patch(String &url, String &data) { + return patch(url.c_str(), data.c_str()); +} + +unsigned int HttpClient::patch(const char *url, const char *data) { + begin("curl"); + if (insecure) { + addParameter("-k"); + } + addParameter("--request"); + addParameter("PATCH"); + addParameter("--data"); + addParameter(data); + addHeader(); + addParameter(url); + return run(); +} + +void HttpClient::patchAsynchronously(String &url, String &data) { + patchAsynchronously(url.c_str(), data.c_str()); +} + +void HttpClient::patchAsynchronously(const char *url, const char *data) { + begin("curl"); + if (insecure) { + addParameter("-k"); + } + addParameter("--request"); + addParameter("PATCH"); + addParameter("--data"); + addParameter(data); + addHeader(); + addParameter(url); + runAsynchronously(); +} + +unsigned int HttpClient::put(String &url, String &data) { + return put(url.c_str(), data.c_str()); +} + +unsigned int HttpClient::put(const char *url, const char *data) { + begin("curl"); + if (insecure) { + addParameter("-k"); + } + addParameter("--request"); + addParameter("PUT"); + addParameter("--data"); + addParameter(data); + addHeader(); + addParameter(url); + return run(); +} + +void HttpClient::putAsynchronously(String &url, String &data) { + putAsynchronously(url.c_str(), data.c_str()); +} + +void HttpClient::putAsynchronously(const char *url, const char *data) { + begin("curl"); + if (insecure) { + addParameter("-k"); + } + addParameter("--request"); + addParameter("PUT"); + addParameter("--data"); + addParameter(data); + addHeader(); + addParameter(url); + runAsynchronously(); +} + +boolean HttpClient::ready() { + return !running(); +} + +unsigned int HttpClient::getResult() { + return exitValue(); +} + +void HttpClient::noCheckSSL() { + insecure = true; +} + +void HttpClient::checkSSL() { + insecure = false; +} + +void HttpClient::setHeader(String &header) { + this->header = header; +} + +void HttpClient::setHeader(const char * header) { + this->header = String(header); +} + +void HttpClient::addHeader() { + if (header.length() > 0) { + addParameter("--header"); + addParameter(header); + } +} + diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/src/HttpClient.h b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/HttpClient.h new file mode 100644 index 000000000..a6e3c77aa --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/HttpClient.h @@ -0,0 +1,59 @@ +/* + Copyright (c) 2013-2014 Arduino LLC. 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 HTTPCLIENT_H_ +#define HTTPCLIENT_H_ + +#include + +class HttpClient : public Process { + public: + HttpClient(); + + unsigned int get(String &url); + unsigned int get(const char * url); + void getAsynchronously(String &url); + void getAsynchronously(const char * url); + unsigned int post(String &url, String &data); + unsigned int post(const char * url, const char * data); + void postAsynchronously(String &url, String &data); + void postAsynchronously(const char * url, const char * data); + unsigned int patch(String &url, String &data); + unsigned int patch(const char * url, const char * data); + void patchAsynchronously(String &url, String &data); + void patchAsynchronously(const char * url, const char * data); + unsigned int put(String &url, String &data); + unsigned int put(const char * url, const char * data); + void putAsynchronously(String &url, String &data); + void putAsynchronously(const char * url, const char * data); + void setHeader(String &header); + void setHeader(const char * header); + boolean ready(); + unsigned int getResult(); + void noCheckSSL(); + void checkSSL(); + + private: + boolean insecure; + + private: + void addHeader(); + String header; +}; + +#endif /* HTTPCLIENT_H_ */ diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/src/Mailbox.cpp b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/Mailbox.cpp new file mode 100644 index 000000000..0c571f73a --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/Mailbox.cpp @@ -0,0 +1,56 @@ +/* + Copyright (c) 2013 Arduino LLC. 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 + +unsigned int MailboxClass::readMessage(uint8_t *buff, unsigned int size) { + uint8_t tmp[] = { 'm' }; + return bridge.transfer(tmp, 1, buff, size); +} + +void MailboxClass::readMessage(String &str, unsigned int maxLength) { + uint8_t tmp[] = { 'm' }; + // XXX: Is there a better way to create the string? + uint8_t buff[maxLength + 1]; + int l = bridge.transfer(tmp, 1, buff, maxLength); + buff[l] = 0; + str = (const char *)buff; +} + +void MailboxClass::writeMessage(const uint8_t *buff, unsigned int size) { + uint8_t cmd[] = {'M'}; + bridge.transfer(cmd, 1, buff, size, NULL, 0); +} + +void MailboxClass::writeMessage(const String& str) { + writeMessage((uint8_t*) str.c_str(), str.length()); +} + +void MailboxClass::writeJSON(const String& str) { + uint8_t cmd[] = {'J'}; + bridge.transfer(cmd, 1, (uint8_t*) str.c_str(), str.length(), NULL, 0); +} + +unsigned int MailboxClass::messageAvailable() { + uint8_t tmp[] = {'n'}; + uint8_t res[2]; + bridge.transfer(tmp, 1, res, 2); + return (res[0] << 8) + res[1]; +} + +MailboxClass Mailbox(Bridge); diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/src/Mailbox.h b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/Mailbox.h new file mode 100644 index 000000000..b2e383308 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/Mailbox.h @@ -0,0 +1,53 @@ +/* + Copyright (c) 2013 Arduino LLC. 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 _MAILBOX_CLASS_H_INCLUDED_ +#define _MAILBOX_CLASS_H_INCLUDED_ + +#include + +class MailboxClass { + public: + MailboxClass(BridgeClass &b = Bridge) : bridge(b) { } + + void begin() { } + void end() { } + + // Receive a message and store it inside a buffer + unsigned int readMessage(uint8_t *buffer, unsigned int size); + // Receive a message and store it inside a String + void readMessage(String &str, unsigned int maxLength = 128); + + // Send a message + void writeMessage(const uint8_t *buffer, unsigned int size); + // Send a message + void writeMessage(const String& str); + // Send a JSON message + void writeJSON(const String& str); + + // Return the size of the next available message, 0 if there are + // no messages in queue. + unsigned int messageAvailable(); + + private: + BridgeClass &bridge; +}; + +extern MailboxClass Mailbox; + +#endif // _MAILBOX_CLASS_H_INCLUDED_ diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/src/Process.cpp b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/Process.cpp new file mode 100644 index 000000000..987f0b8ac --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/Process.cpp @@ -0,0 +1,142 @@ +/* + Copyright (c) 2013 Arduino LLC. 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 + +Process::~Process() { + close(); +} + +size_t Process::write(uint8_t c) { + uint8_t cmd[] = {'I', handle, c}; + bridge.transfer(cmd, 3); + return 1; +} + +void Process::flush() { +} + +int Process::available() { + // Look if there is new data available + doBuffer(); + return buffered; +} + +int Process::read() { + doBuffer(); + if (buffered == 0) + return -1; // no chars available + else { + buffered--; + return buffer[readPos++]; + } +} + +int Process::peek() { + doBuffer(); + if (buffered == 0) + return -1; // no chars available + else + return buffer[readPos]; +} + +void Process::doBuffer() { + // If there are already char in buffer exit + if (buffered > 0) + return; + + // Try to buffer up to 32 characters + readPos = 0; + uint8_t cmd[] = {'O', handle, sizeof(buffer)}; + buffered = bridge.transfer(cmd, 3, buffer, sizeof(buffer)); +} + +void Process::begin(const String &command) { + close(); + cmdline = new String(command); +} + +void Process::addParameter(const String ¶m) { + *cmdline += "\xFE"; + *cmdline += param; +} + +void Process::runAsynchronously() { + uint8_t cmd[] = {'R'}; + uint8_t res[2]; + bridge.transfer(cmd, 1, (uint8_t*)cmdline->c_str(), cmdline->length(), res, 2); + handle = res[1]; + + delete cmdline; + cmdline = NULL; + + if (res[0] == 0) // res[0] contains error code + started = true; +} + +boolean Process::running() { + uint8_t cmd[] = {'r', handle}; + uint8_t res[1]; + bridge.transfer(cmd, 2, res, 1); + return (res[0] == 1); +} + +unsigned int Process::exitValue() { + uint8_t cmd[] = {'W', handle}; + uint8_t res[2]; + bridge.transfer(cmd, 2, res, 2); + return (res[0] << 8) + res[1]; +} + +unsigned int Process::run() { + runAsynchronously(); + while (running()) + delay(100); + return exitValue(); +} + +void Process::close() { + if (started) { + uint8_t cmd[] = {'w', handle}; + bridge.transfer(cmd, 2); + } + started = false; +} + +unsigned int Process::runShellCommand(const String &command) { + runShellCommandAsynchronously(command); + while (running()) + delay(100); + return exitValue(); +} + +void Process::runShellCommandAsynchronously(const String &command) { + begin("/bin/ash"); + addParameter("-c"); + addParameter(command); + runAsynchronously(); +} + +// This method is currently unused +//static unsigned int __commandOutputAvailable(uint8_t handle) { +// uint8_t cmd[] = {'o', handle}; +// uint8_t res[1]; +// Bridge.transfer(cmd, 2, res, 1); +// return res[0]; +//} + diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/src/Process.h b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/Process.h new file mode 100644 index 000000000..7002764a0 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/Process.h @@ -0,0 +1,71 @@ +/* + Copyright (c) 2013 Arduino LLC. 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 PROCESS_H_ +#define PROCESS_H_ + +#include + +class Process : public Stream { + public: + // Constructor with a user provided BridgeClass instance + Process(BridgeClass &_b = Bridge) : + bridge(_b), started(false), buffered(0), readPos(0) { } + ~Process(); + + void begin(const String &command); + void addParameter(const String ¶m); + unsigned int run(); + void runAsynchronously(); + boolean running(); + unsigned int exitValue(); + void close(); + + unsigned int runShellCommand(const String &command); + void runShellCommandAsynchronously(const String &command); + + operator bool () { + return started; + } + + // Stream methods + // (read from process stdout) + int available(); + int read(); + int peek(); + // (write to process stdin) + size_t write(uint8_t); + void flush(); + // TODO: add optimized function for block write + + private: + BridgeClass &bridge; + uint8_t handle; + String *cmdline; + boolean started; + + private: + void doBuffer(); + uint8_t buffered; + uint8_t readPos; + static const int BUFFER_SIZE = 64; + uint8_t buffer[BUFFER_SIZE]; + +}; + +#endif diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/src/YunClient.h b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/YunClient.h new file mode 100644 index 000000000..faff247c9 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/YunClient.h @@ -0,0 +1,27 @@ +/* + Copyright (c) 2014 Arduino LLC. 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 _YUN_CLIENT_H_ +#define _YUN_CLIENT_H_ + +#include + +#warning "The use of YunClient is deprecated. Use BridgeClient instead!" +typedef BridgeClient YunClient; + +#endif // _YUN_CLIENT_H_ diff --git a/app/testdata/libraries/Bridge_1.7.0/Bridge/src/YunServer.h b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/YunServer.h new file mode 100644 index 000000000..95d05cd71 --- /dev/null +++ b/app/testdata/libraries/Bridge_1.7.0/Bridge/src/YunServer.h @@ -0,0 +1,27 @@ +/* + Copyright (c) 2014 Arduino LLC. 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 _YUN_SERVER_H_ +#define _YUN_SERVER_H_ + +#include + +#warning "The use of YunServer is deprecated. Use BridgeServer instead!" +typedef BridgeServer YunServer; + +#endif // _YUN_SERVER_H_ diff --git a/app/testdata/libraries/SD_1.1.1/SD/README.adoc b/app/testdata/libraries/SD_1.1.1/SD/README.adoc new file mode 100644 index 000000000..fabff563c --- /dev/null +++ b/app/testdata/libraries/SD_1.1.1/SD/README.adoc @@ -0,0 +1,24 @@ += SD Library for Arduino = + +The SD library allows for reading from and writing to SD cards. + +For more information about this library please visit us at +http://www.arduino.cc/en/Reference/SD + +== License == + + Copyright (C) 2009 by William Greiman +Copyright (c) 2010 SparkFun Electronics + +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 3 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, see . diff --git a/app/testdata/libraries/SD_1.1.1/SD/examples/CardInfo/CardInfo.ino b/app/testdata/libraries/SD_1.1.1/SD/examples/CardInfo/CardInfo.ino new file mode 100644 index 000000000..69292de85 --- /dev/null +++ b/app/testdata/libraries/SD_1.1.1/SD/examples/CardInfo/CardInfo.ino @@ -0,0 +1,112 @@ +/* + SD card test + + This example shows how use the utility libraries on which the' + SD library is based in order to get info about your SD card. + Very useful for testing a card when you're not sure whether its working or not. + + The circuit: + * SD card attached to SPI bus as follows: + ** MOSI - pin 11 on Arduino Uno/Duemilanove/Diecimila + ** MISO - pin 12 on Arduino Uno/Duemilanove/Diecimila + ** CLK - pin 13 on Arduino Uno/Duemilanove/Diecimila + ** CS - depends on your SD card shield or module. + Pin 4 used here for consistency with other Arduino examples + + + created 28 Mar 2011 + by Limor Fried + modified 9 Apr 2012 + by Tom Igoe + */ +// include the SD library: +#include +#include + +// set up variables using the SD utility library functions: +Sd2Card card; +SdVolume volume; +SdFile root; + +// change this to match your SD shield or module; +// Arduino Ethernet shield: pin 4 +// Adafruit SD shields and modules: pin 10 +// Sparkfun SD shield: pin 8 +// MKRZero SD: SDCARD_SS_PIN +const int chipSelect = 4; + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + + Serial.print("\nInitializing SD card..."); + + // we'll use the initialization code from the utility libraries + // since we're just testing if the card is working! + if (!card.init(SPI_HALF_SPEED, chipSelect)) { + Serial.println("initialization failed. Things to check:"); + Serial.println("* is a card inserted?"); + Serial.println("* is your wiring correct?"); + Serial.println("* did you change the chipSelect pin to match your shield or module?"); + return; + } else { + Serial.println("Wiring is correct and a card is present."); + } + + // print the type of card + Serial.print("\nCard type: "); + switch (card.type()) { + case SD_CARD_TYPE_SD1: + Serial.println("SD1"); + break; + case SD_CARD_TYPE_SD2: + Serial.println("SD2"); + break; + case SD_CARD_TYPE_SDHC: + Serial.println("SDHC"); + break; + default: + Serial.println("Unknown"); + } + + // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32 + if (!volume.init(card)) { + Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card"); + return; + } + + + // print the type and size of the first FAT-type volume + uint32_t volumesize; + Serial.print("\nVolume type is FAT"); + Serial.println(volume.fatType(), DEC); + Serial.println(); + + volumesize = volume.blocksPerCluster(); // clusters are collections of blocks + volumesize *= volume.clusterCount(); // we'll have a lot of clusters + volumesize *= 512; // SD card blocks are always 512 bytes + Serial.print("Volume size (bytes): "); + Serial.println(volumesize); + Serial.print("Volume size (Kbytes): "); + volumesize /= 1024; + Serial.println(volumesize); + Serial.print("Volume size (Mbytes): "); + volumesize /= 1024; + Serial.println(volumesize); + + + Serial.println("\nFiles found on the card (name, date and size in bytes): "); + root.openRoot(volume); + + // list all files in the card with date and size + root.ls(LS_R | LS_DATE | LS_SIZE); +} + + +void loop(void) { + +} diff --git a/app/testdata/libraries/SD_1.1.1/SD/examples/Datalogger/Datalogger.ino b/app/testdata/libraries/SD_1.1.1/SD/examples/Datalogger/Datalogger.ino new file mode 100644 index 000000000..c17096492 --- /dev/null +++ b/app/testdata/libraries/SD_1.1.1/SD/examples/Datalogger/Datalogger.ino @@ -0,0 +1,84 @@ +/* + SD card datalogger + + This example shows how to log data from three analog sensors + to an SD card using the SD library. + + The circuit: + * analog sensors on analog ins 0, 1, and 2 + * SD card attached to SPI bus as follows: + ** MOSI - pin 11 + ** MISO - pin 12 + ** CLK - pin 13 + ** CS - pin 4 (for MKRZero SD: SDCARD_SS_PIN) + + created 24 Nov 2010 + modified 9 Apr 2012 + by Tom Igoe + + This example code is in the public domain. + + */ + +#include +#include + +const int chipSelect = 4; + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + + Serial.print("Initializing SD card..."); + + // see if the card is present and can be initialized: + if (!SD.begin(chipSelect)) { + Serial.println("Card failed, or not present"); + // don't do anything more: + return; + } + Serial.println("card initialized."); +} + +void loop() { + // make a string for assembling the data to log: + String dataString = ""; + + // read three sensors and append to the string: + for (int analogPin = 0; analogPin < 3; analogPin++) { + int sensor = analogRead(analogPin); + dataString += String(sensor); + if (analogPin < 2) { + dataString += ","; + } + } + + // open the file. note that only one file can be open at a time, + // so you have to close this one before opening another. + File dataFile = SD.open("datalog.txt", FILE_WRITE); + + // if the file is available, write to it: + if (dataFile) { + dataFile.println(dataString); + dataFile.close(); + // print to the serial port too: + Serial.println(dataString); + } + // if the file isn't open, pop up an error: + else { + Serial.println("error opening datalog.txt"); + } +} + + + + + + + + + diff --git a/app/testdata/libraries/SD_1.1.1/SD/examples/DumpFile/DumpFile.ino b/app/testdata/libraries/SD_1.1.1/SD/examples/DumpFile/DumpFile.ino new file mode 100644 index 000000000..b9a8dbf12 --- /dev/null +++ b/app/testdata/libraries/SD_1.1.1/SD/examples/DumpFile/DumpFile.ino @@ -0,0 +1,65 @@ +/* + SD card file dump + + This example shows how to read a file from the SD card using the + SD library and send it over the serial port. + + The circuit: + * SD card attached to SPI bus as follows: + ** MOSI - pin 11 + ** MISO - pin 12 + ** CLK - pin 13 + ** CS - pin 4 (for MKRZero SD: SDCARD_SS_PIN) + + created 22 December 2010 + by Limor Fried + modified 9 Apr 2012 + by Tom Igoe + + This example code is in the public domain. + + */ + +#include +#include + +const int chipSelect = 4; + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + + Serial.print("Initializing SD card..."); + + // see if the card is present and can be initialized: + if (!SD.begin(chipSelect)) { + Serial.println("Card failed, or not present"); + // don't do anything more: + return; + } + Serial.println("card initialized."); + + // open the file. note that only one file can be open at a time, + // so you have to close this one before opening another. + File dataFile = SD.open("datalog.txt"); + + // if the file is available, write to it: + if (dataFile) { + while (dataFile.available()) { + Serial.write(dataFile.read()); + } + dataFile.close(); + } + // if the file isn't open, pop up an error: + else { + Serial.println("error opening datalog.txt"); + } +} + +void loop() { +} + diff --git a/app/testdata/libraries/SD_1.1.1/SD/examples/Files/Files.ino b/app/testdata/libraries/SD_1.1.1/SD/examples/Files/Files.ino new file mode 100644 index 000000000..1468f9c72 --- /dev/null +++ b/app/testdata/libraries/SD_1.1.1/SD/examples/Files/Files.ino @@ -0,0 +1,75 @@ +/* + SD card basic file example + + This example shows how to create and destroy an SD card file + The circuit: + * SD card attached to SPI bus as follows: + ** MOSI - pin 11 + ** MISO - pin 12 + ** CLK - pin 13 + ** CS - pin 4 (for MKRZero SD: SDCARD_SS_PIN) + + created Nov 2010 + by David A. Mellis + modified 9 Apr 2012 + by Tom Igoe + + This example code is in the public domain. + + */ +#include +#include + +File myFile; + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + + Serial.print("Initializing SD card..."); + + if (!SD.begin(4)) { + Serial.println("initialization failed!"); + return; + } + Serial.println("initialization done."); + + if (SD.exists("example.txt")) { + Serial.println("example.txt exists."); + } else { + Serial.println("example.txt doesn't exist."); + } + + // open a new file and immediately close it: + Serial.println("Creating example.txt..."); + myFile = SD.open("example.txt", FILE_WRITE); + myFile.close(); + + // Check to see if the file exists: + if (SD.exists("example.txt")) { + Serial.println("example.txt exists."); + } else { + Serial.println("example.txt doesn't exist."); + } + + // delete the file: + Serial.println("Removing example.txt..."); + SD.remove("example.txt"); + + if (SD.exists("example.txt")) { + Serial.println("example.txt exists."); + } else { + Serial.println("example.txt doesn't exist."); + } +} + +void loop() { + // nothing happens after setup finishes. +} + + + diff --git a/app/testdata/libraries/SD_1.1.1/SD/examples/ReadWrite/ReadWrite.ino b/app/testdata/libraries/SD_1.1.1/SD/examples/ReadWrite/ReadWrite.ino new file mode 100644 index 000000000..c81f1538d --- /dev/null +++ b/app/testdata/libraries/SD_1.1.1/SD/examples/ReadWrite/ReadWrite.ino @@ -0,0 +1,79 @@ +/* + SD card read/write + + This example shows how to read and write data to and from an SD card file + The circuit: + * SD card attached to SPI bus as follows: + ** MOSI - pin 11 + ** MISO - pin 12 + ** CLK - pin 13 + ** CS - pin 4 (for MKRZero SD: SDCARD_SS_PIN) + + created Nov 2010 + by David A. Mellis + modified 9 Apr 2012 + by Tom Igoe + + This example code is in the public domain. + + */ + +#include +#include + +File myFile; + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + + Serial.print("Initializing SD card..."); + + if (!SD.begin(4)) { + Serial.println("initialization failed!"); + return; + } + Serial.println("initialization done."); + + // open the file. note that only one file can be open at a time, + // so you have to close this one before opening another. + myFile = SD.open("test.txt", FILE_WRITE); + + // if the file opened okay, write to it: + if (myFile) { + Serial.print("Writing to test.txt..."); + myFile.println("testing 1, 2, 3."); + // close the file: + myFile.close(); + Serial.println("done."); + } else { + // if the file didn't open, print an error: + Serial.println("error opening test.txt"); + } + + // re-open the file for reading: + myFile = SD.open("test.txt"); + if (myFile) { + Serial.println("test.txt:"); + + // read from the file until there's nothing else in it: + while (myFile.available()) { + Serial.write(myFile.read()); + } + // close the file: + myFile.close(); + } else { + // if the file didn't open, print an error: + Serial.println("error opening test.txt"); + } +} + +void loop() { + // nothing happens after setup +} + + diff --git a/app/testdata/libraries/SD_1.1.1/SD/examples/listfiles/listfiles.ino b/app/testdata/libraries/SD_1.1.1/SD/examples/listfiles/listfiles.ino new file mode 100644 index 000000000..589bffd2f --- /dev/null +++ b/app/testdata/libraries/SD_1.1.1/SD/examples/listfiles/listfiles.ino @@ -0,0 +1,80 @@ +/* + Listfiles + + 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 + ** MISO - pin 12 + ** CLK - pin 13 + ** CS - pin 4 (for MKRZero SD: SDCARD_SS_PIN) + + created Nov 2010 + 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. + + */ +#include +#include + +File root; + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + Serial.print("Initializing SD card..."); + + if (!SD.begin(4)) { + Serial.println("initialization failed!"); + return; + } + Serial.println("initialization done."); + + root = SD.open("/"); + + printDirectory(root, 0); + + Serial.println("done!"); +} + +void loop() { + // nothing happens after setup finishes. +} + +void printDirectory(File dir, int numTabs) { + while (true) { + + File entry = dir.openNextFile(); + if (! entry) { + // no more files + break; + } + for (uint8_t i = 0; i < numTabs; i++) { + Serial.print('\t'); + } + Serial.print(entry.name()); + if (entry.isDirectory()) { + Serial.println("/"); + printDirectory(entry, numTabs + 1); + } else { + // files have sizes, directories do not + Serial.print("\t\t"); + Serial.println(entry.size(), DEC); + } + entry.close(); + } +} + + + diff --git a/app/testdata/libraries/SD_1.1.1/SD/keywords.txt b/app/testdata/libraries/SD_1.1.1/SD/keywords.txt new file mode 100644 index 000000000..91e74b830 --- /dev/null +++ b/app/testdata/libraries/SD_1.1.1/SD/keywords.txt @@ -0,0 +1,31 @@ +####################################### +# Syntax Coloring Map SD +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +SD KEYWORD1 SD +File KEYWORD1 SD +SDFile KEYWORD1 SD + +####################################### +# Methods and Functions (KEYWORD2) +####################################### +begin KEYWORD2 +exists KEYWORD2 +mkdir KEYWORD2 +remove KEYWORD2 +rmdir KEYWORD2 +open KEYWORD2 +close KEYWORD2 +seek KEYWORD2 +position KEYWORD2 +size KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### +FILE_READ LITERAL1 +FILE_WRITE LITERAL1 diff --git a/app/testdata/libraries/SD_1.1.1/SD/library.properties b/app/testdata/libraries/SD_1.1.1/SD/library.properties new file mode 100644 index 000000000..abdfb9d00 --- /dev/null +++ b/app/testdata/libraries/SD_1.1.1/SD/library.properties @@ -0,0 +1,9 @@ +name=SD +version=1.1.1 +author=Arduino, SparkFun +maintainer=Arduino +sentence=Enables reading and writing on SD cards. +paragraph=Once an SD memory card is connected to the SPI interface of the Arduino or Genuino board you can create files and read/write on them. You can also move through directories on the SD card. +category=Data Storage +url=http://www.arduino.cc/en/Reference/SD +architectures=* diff --git a/app/testdata/libraries/SD_1.1.1/SD/src/File.cpp b/app/testdata/libraries/SD_1.1.1/SD/src/File.cpp new file mode 100644 index 000000000..6eee39aa1 --- /dev/null +++ b/app/testdata/libraries/SD_1.1.1/SD/src/File.cpp @@ -0,0 +1,146 @@ +/* + + SD - a slightly more friendly wrapper for sdfatlib + + This library aims to expose a subset of SD card functionality + in the form of a higher level "wrapper" object. + + License: GNU General Public License V3 + (Because sdfatlib is licensed with this.) + + (C) Copyright 2010 SparkFun Electronics + + */ + +#include + +/* for debugging file open/close leaks + uint8_t nfilecount=0; +*/ + +File::File(SdFile f, const char *n) { + // oh man you are kidding me, new() doesnt exist? Ok we do it by hand! + _file = (SdFile *)malloc(sizeof(SdFile)); + if (_file) { + memcpy(_file, &f, sizeof(SdFile)); + + strncpy(_name, n, 12); + _name[12] = 0; + + /* for debugging file open/close leaks + nfilecount++; + Serial.print("Created \""); + Serial.print(n); + Serial.print("\": "); + Serial.println(nfilecount, DEC); + */ + } +} + +File::File(void) { + _file = 0; + _name[0] = 0; + //Serial.print("Created empty file object"); +} + +// returns a pointer to the file name +char *File::name(void) { + return _name; +} + +// a directory is a special type of file +boolean File::isDirectory(void) { + return (_file && _file->isDir()); +} + + +size_t File::write(uint8_t val) { + return write(&val, 1); +} + +size_t File::write(const uint8_t *buf, size_t size) { + size_t t; + if (!_file) { + setWriteError(); + return 0; + } + _file->clearWriteError(); + t = _file->write(buf, size); + if (_file->getWriteError()) { + setWriteError(); + return 0; + } + return t; +} + +int File::peek() { + if (! _file) + return 0; + + int c = _file->read(); + if (c != -1) _file->seekCur(-1); + return c; +} + +int File::read() { + if (_file) + return _file->read(); + return -1; +} + +// buffered read for more efficient, high speed reading +int File::read(void *buf, uint16_t nbyte) { + if (_file) + return _file->read(buf, nbyte); + return 0; +} + +int File::available() { + if (! _file) return 0; + + uint32_t n = size() - position(); + + return n > 0X7FFF ? 0X7FFF : n; +} + +void File::flush() { + if (_file) + _file->sync(); +} + +boolean File::seek(uint32_t pos) { + if (! _file) return false; + + return _file->seekSet(pos); +} + +uint32_t File::position() { + if (! _file) return -1; + return _file->curPosition(); +} + +uint32_t File::size() { + if (! _file) return 0; + return _file->fileSize(); +} + +void File::close() { + if (_file) { + _file->close(); + free(_file); + _file = 0; + + /* for debugging file open/close leaks + nfilecount--; + Serial.print("Deleted "); + Serial.println(nfilecount, DEC); + */ + } +} + +File::operator bool() { + if (_file) + return _file->isOpen(); + return false; +} + diff --git a/app/testdata/libraries/SD_1.1.1/SD/src/README.txt b/app/testdata/libraries/SD_1.1.1/SD/src/README.txt new file mode 100644 index 000000000..495ea4c79 --- /dev/null +++ b/app/testdata/libraries/SD_1.1.1/SD/src/README.txt @@ -0,0 +1,13 @@ + +** SD - a slightly more friendly wrapper for sdfatlib ** + +This library aims to expose a subset of SD card functionality in the +form of a higher level "wrapper" object. + +License: GNU General Public License V3 + (Because sdfatlib is licensed with this.) + +(C) Copyright 2010 SparkFun Electronics + +Now better than ever with optimization, multiple file support, directory handling, etc - ladyada! + diff --git a/app/testdata/libraries/SD_1.1.1/SD/src/SD.cpp b/app/testdata/libraries/SD_1.1.1/SD/src/SD.cpp new file mode 100644 index 000000000..b88c665fc --- /dev/null +++ b/app/testdata/libraries/SD_1.1.1/SD/src/SD.cpp @@ -0,0 +1,625 @@ +/* + + SD - a slightly more friendly wrapper for sdfatlib + + This library aims to expose a subset of SD card functionality + in the form of a higher level "wrapper" object. + + License: GNU General Public License V3 + (Because sdfatlib is licensed with this.) + + (C) Copyright 2010 SparkFun Electronics + + + This library provides four key benefits: + + * Including `SD.h` automatically creates a global + `SD` object which can be interacted with in a similar + manner to other standard global objects like `Serial` and `Ethernet`. + + * Boilerplate initialisation code is contained in one method named + `begin` and no further objects need to be created in order to access + the SD card. + + * Calls to `open` can supply a full path name including parent + directories which simplifies interacting with files in subdirectories. + + * Utility methods are provided to determine whether a file exists + and to create a directory heirarchy. + + + Note however that not all functionality provided by the underlying + sdfatlib library is exposed. + + */ + +/* + + Implementation Notes + + In order to handle multi-directory path traversal, functionality that + requires this ability is implemented as callback functions. + + Individual methods call the `walkPath` function which performs the actual + directory traversal (swapping between two different directory/file handles + along the way) and at each level calls the supplied callback function. + + Some types of functionality will take an action at each level (e.g. exists + or make directory) which others will only take an action at the bottom + level (e.g. open). + + */ + +#include "SD.h" + +namespace SDLib { + +// Used by `getNextPathComponent` +#define MAX_COMPONENT_LEN 12 // What is max length? +#define PATH_COMPONENT_BUFFER_LEN MAX_COMPONENT_LEN+1 + +bool getNextPathComponent(const char *path, unsigned int *p_offset, + char *buffer) { + /* + + Parse individual path components from a path. + + e.g. after repeated calls '/foo/bar/baz' will be split + into 'foo', 'bar', 'baz'. + + This is similar to `strtok()` but copies the component into the + supplied buffer rather than modifying the original string. + + + `buffer` needs to be PATH_COMPONENT_BUFFER_LEN in size. + + `p_offset` needs to point to an integer of the offset at + which the previous path component finished. + + Returns `true` if more components remain. + + Returns `false` if this is the last component. + (This means path ended with 'foo' or 'foo/'.) + + */ + + // TODO: Have buffer local to this function, so we know it's the + // correct length? + + int bufferOffset = 0; + + int offset = *p_offset; + + // Skip root or other separator + if (path[offset] == '/') { + offset++; + } + + // Copy the next next path segment + while (bufferOffset < MAX_COMPONENT_LEN + && (path[offset] != '/') + && (path[offset] != '\0')) { + buffer[bufferOffset++] = path[offset++]; + } + + buffer[bufferOffset] = '\0'; + + // Skip trailing separator so we can determine if this + // is the last component in the path or not. + if (path[offset] == '/') { + offset++; + } + + *p_offset = offset; + + return (path[offset] != '\0'); +} + + + +boolean walkPath(const char *filepath, SdFile& parentDir, + boolean (*callback)(SdFile& parentDir, + const char *filePathComponent, + boolean isLastComponent, + void *object), + void *object = NULL) { + /* + + When given a file path (and parent directory--normally root), + this function traverses the directories in the path and at each + level calls the supplied callback function while also providing + the supplied object for context if required. + + e.g. given the path '/foo/bar/baz' + the callback would be called at the equivalent of + '/foo', '/foo/bar' and '/foo/bar/baz'. + + The implementation swaps between two different directory/file + handles as it traverses the directories and does not use recursion + in an attempt to use memory efficiently. + + If a callback wishes to stop the directory traversal it should + return false--in this case the function will stop the traversal, + tidy up and return false. + + If a directory path doesn't exist at some point this function will + also return false and not subsequently call the callback. + + If a directory path specified is complete, valid and the callback + did not indicate the traversal should be interrupted then this + function will return true. + + */ + + + SdFile subfile1; + SdFile subfile2; + + char buffer[PATH_COMPONENT_BUFFER_LEN]; + + unsigned int offset = 0; + + SdFile *p_parent; + SdFile *p_child; + + SdFile *p_tmp_sdfile; + + p_child = &subfile1; + + p_parent = &parentDir; + + while (true) { + + boolean moreComponents = getNextPathComponent(filepath, &offset, buffer); + + boolean shouldContinue = callback((*p_parent), buffer, !moreComponents, object); + + if (!shouldContinue) { + // TODO: Don't repeat this code? + // If it's one we've created then we + // don't need the parent handle anymore. + if (p_parent != &parentDir) { + (*p_parent).close(); + } + return false; + } + + if (!moreComponents) { + break; + } + + boolean exists = (*p_child).open(*p_parent, buffer, O_RDONLY); + + // If it's one we've created then we + // don't need the parent handle anymore. + if (p_parent != &parentDir) { + (*p_parent).close(); + } + + // Handle case when it doesn't exist and we can't continue... + if (exists) { + // We alternate between two file handles as we go down + // the path. + if (p_parent == &parentDir) { + p_parent = &subfile2; + } + + p_tmp_sdfile = p_parent; + p_parent = p_child; + p_child = p_tmp_sdfile; + } else { + return false; + } + } + + if (p_parent != &parentDir) { + (*p_parent).close(); // TODO: Return/ handle different? + } + + return true; +} + + + +/* + + The callbacks used to implement various functionality follow. + + Each callback is supplied with a parent directory handle, + character string with the name of the current file path component, + a flag indicating if this component is the last in the path and + a pointer to an arbitrary object used for context. + + */ + +boolean callback_pathExists(SdFile& parentDir, const char *filePathComponent, + boolean /* isLastComponent */, void * /* object */) { + /* + + Callback used to determine if a file/directory exists in parent + directory. + + Returns true if file path exists. + + */ + SdFile child; + + boolean exists = child.open(parentDir, filePathComponent, O_RDONLY); + + if (exists) { + child.close(); + } + + return exists; +} + + + +boolean callback_makeDirPath(SdFile& parentDir, const char *filePathComponent, + boolean isLastComponent, void *object) { + /* + + Callback used to create a directory in the parent directory if + it does not already exist. + + Returns true if a directory was created or it already existed. + + */ + boolean result = false; + SdFile child; + + result = callback_pathExists(parentDir, filePathComponent, isLastComponent, object); + if (!result) { + result = child.makeDir(parentDir, filePathComponent); + } + + return result; +} + + + /* + +boolean callback_openPath(SdFile& parentDir, char *filePathComponent, + boolean isLastComponent, void *object) { + + Callback used to open a file specified by a filepath that may + specify one or more directories above it. + + Expects the context object to be an instance of `SDClass` and + will use the `file` property of the instance to open the requested + file/directory with the associated file open mode property. + + Always returns true if the directory traversal hasn't reached the + bottom of the directory heirarchy. + + Returns false once the file has been opened--to prevent the traversal + from descending further. (This may be unnecessary.) + + if (isLastComponent) { + SDClass *p_SD = static_cast(object); + p_SD->file.open(parentDir, filePathComponent, p_SD->fileOpenMode); + if (p_SD->fileOpenMode == FILE_WRITE) { + p_SD->file.seekSet(p_SD->file.fileSize()); + } + // TODO: Return file open result? + return false; + } + return true; +} + */ + + + +boolean callback_remove(SdFile& parentDir, const char *filePathComponent, + boolean isLastComponent, void * /* object */) { + if (isLastComponent) { + return SdFile::remove(parentDir, filePathComponent); + } + return true; +} + +boolean callback_rmdir(SdFile& parentDir, const char *filePathComponent, + boolean isLastComponent, void * /* object */) { + if (isLastComponent) { + SdFile f; + if (!f.open(parentDir, filePathComponent, O_READ)) return false; + return f.rmDir(); + } + return true; +} + + + +/* Implementation of class used to create `SDCard` object. */ + + + +boolean SDClass::begin(uint8_t csPin) { + /* + + Performs the initialisation required by the sdfatlib library. + + Return true if initialization succeeds, false otherwise. + + */ + return card.init(SPI_HALF_SPEED, csPin) && + volume.init(card) && + root.openRoot(volume); +} + +boolean SDClass::begin(uint32_t clock, uint8_t csPin) { + return card.init(SPI_HALF_SPEED, csPin) && + card.setSpiClock(clock) && + volume.init(card) && + root.openRoot(volume); +} + +// this little helper is used to traverse paths +SdFile SDClass::getParentDir(const char *filepath, int *index) { + // get parent directory + SdFile d1 = root; // start with the mostparent, root! + SdFile d2; + + // we'll use the pointers to swap between the two objects + SdFile *parent = &d1; + SdFile *subdir = &d2; + + const char *origpath = filepath; + + while (strchr(filepath, '/')) { + + // get rid of leading /'s + if (filepath[0] == '/') { + filepath++; + continue; + } + + if (! strchr(filepath, '/')) { + // it was in the root directory, so leave now + break; + } + + // extract just the name of the next subdirectory + uint8_t idx = strchr(filepath, '/') - filepath; + if (idx > 12) + idx = 12; // dont let them specify long names + char subdirname[13]; + strncpy(subdirname, filepath, idx); + subdirname[idx] = 0; + + // close the subdir (we reuse them) if open + subdir->close(); + if (! subdir->open(parent, subdirname, O_READ)) { + // failed to open one of the subdirectories + return SdFile(); + } + // move forward to the next subdirectory + filepath += idx; + + // we reuse the objects, close it. + parent->close(); + + // swap the pointers + SdFile *t = parent; + parent = subdir; + subdir = t; + } + + *index = (int)(filepath - origpath); + // parent is now the parent diretory of the file! + return *parent; +} + + +File SDClass::open(const char *filepath, uint8_t mode) { + /* + + Open the supplied file path for reading or writing. + + The file content can be accessed via the `file` property of + the `SDClass` object--this property is currently + a standard `SdFile` object from `sdfatlib`. + + Defaults to read only. + + If `write` is true, default action (when `append` is true) is to + append data to the end of the file. + + If `append` is false then the file will be truncated first. + + If the file does not exist and it is opened for writing the file + will be created. + + An attempt to open a file for reading that does not exist is an + error. + + */ + + int pathidx; + + // do the interative search + SdFile parentdir = getParentDir(filepath, &pathidx); + // no more subdirs! + + filepath += pathidx; + + if (! filepath[0]) { + // it was the directory itself! + return File(parentdir, "/"); + } + + // Open the file itself + SdFile file; + + // failed to open a subdir! + if (!parentdir.isOpen()) + return File(); + + // there is a special case for the Root directory since its a static dir + if (parentdir.isRoot()) { + if ( ! file.open(root, filepath, mode)) { + // failed to open the file :( + return File(); + } + // dont close the root! + } else { + if ( ! file.open(parentdir, filepath, mode)) { + return File(); + } + // close the parent + parentdir.close(); + } + + if (mode & (O_APPEND | O_WRITE)) + file.seekSet(file.fileSize()); + return File(file, filepath); +} + + +/* +File SDClass::open(char *filepath, uint8_t mode) { + // + + Open the supplied file path for reading or writing. + + The file content can be accessed via the `file` property of + the `SDClass` object--this property is currently + a standard `SdFile` object from `sdfatlib`. + + Defaults to read only. + + If `write` is true, default action (when `append` is true) is to + append data to the end of the file. + + If `append` is false then the file will be truncated first. + + If the file does not exist and it is opened for writing the file + will be created. + + An attempt to open a file for reading that does not exist is an + error. + + // + + // TODO: Allow for read&write? (Possibly not, as it requires seek.) + + fileOpenMode = mode; + walkPath(filepath, root, callback_openPath, this); + + return File(); + +} +*/ + + +//boolean SDClass::close() { +// /* +// +// Closes the file opened by the `open` method. +// +// */ +// file.close(); +//} + + +boolean SDClass::exists(const char *filepath) { + /* + + Returns true if the supplied file path exists. + + */ + return walkPath(filepath, root, callback_pathExists); +} + + +//boolean SDClass::exists(char *filepath, SdFile& parentDir) { +// /* +// +// Returns true if the supplied file path rooted at `parentDir` +// exists. +// +// */ +// return walkPath(filepath, parentDir, callback_pathExists); +//} + + +boolean SDClass::mkdir(const char *filepath) { + /* + + Makes a single directory or a heirarchy of directories. + + A rough equivalent to `mkdir -p`. + + */ + return walkPath(filepath, root, callback_makeDirPath); +} + +boolean SDClass::rmdir(const char *filepath) { + /* + + Remove a single directory or a heirarchy of directories. + + A rough equivalent to `rm -rf`. + + */ + return walkPath(filepath, root, callback_rmdir); +} + +boolean SDClass::remove(const char *filepath) { + return walkPath(filepath, root, callback_remove); +} + + +// allows you to recurse into a directory +File File::openNextFile(uint8_t mode) { + dir_t p; + + //Serial.print("\t\treading dir..."); + while (_file->readDir(&p) > 0) { + + // done if past last used entry + if (p.name[0] == DIR_NAME_FREE) { + //Serial.println("end"); + return File(); + } + + // skip deleted entry and entries for . and .. + if (p.name[0] == DIR_NAME_DELETED || p.name[0] == '.') { + //Serial.println("dots"); + continue; + } + + // only list subdirectories and files + if (!DIR_IS_FILE_OR_SUBDIR(&p)) { + //Serial.println("notafile"); + continue; + } + + // print file name with possible blank fill + SdFile f; + char name[13]; + _file->dirName(p, name); + //Serial.print("try to open file "); + //Serial.println(name); + + if (f.open(_file, name, mode)) { + //Serial.println("OK!"); + return File(f, name); + } else { + //Serial.println("ugh"); + return File(); + } + } + + //Serial.println("nothing"); + return File(); +} + +void File::rewindDirectory(void) { + if (isDirectory()) + _file->rewind(); +} + +SDClass SD; + +}; diff --git a/app/testdata/libraries/SD_1.1.1/SD/src/SD.h b/app/testdata/libraries/SD_1.1.1/SD/src/SD.h new file mode 100644 index 000000000..7f41033ec --- /dev/null +++ b/app/testdata/libraries/SD_1.1.1/SD/src/SD.h @@ -0,0 +1,124 @@ +/* + + SD - a slightly more friendly wrapper for sdfatlib + + This library aims to expose a subset of SD card functionality + in the form of a higher level "wrapper" object. + + License: GNU General Public License V3 + (Because sdfatlib is licensed with this.) + + (C) Copyright 2010 SparkFun Electronics + + */ + +#ifndef __SD_H__ +#define __SD_H__ + +#include + +#include +#include + +#define FILE_READ O_READ +#define FILE_WRITE (O_READ | O_WRITE | O_CREAT) + +namespace SDLib { + +class File : public Stream { + private: + char _name[13]; // our name + SdFile *_file; // underlying file pointer + +public: + File(SdFile f, const char *name); // wraps an underlying SdFile + File(void); // 'empty' constructor + virtual size_t write(uint8_t); + virtual size_t write(const uint8_t *buf, size_t size); + virtual int read(); + virtual int peek(); + virtual int available(); + virtual void flush(); + int read(void *buf, uint16_t nbyte); + boolean seek(uint32_t pos); + uint32_t position(); + uint32_t size(); + void close(); + operator bool(); + char * name(); + + boolean isDirectory(void); + File openNextFile(uint8_t mode = O_RDONLY); + void rewindDirectory(void); + + using Print::write; +}; + +class SDClass { + +private: + // These are required for initialisation and use of sdfatlib + Sd2Card card; + SdVolume volume; + SdFile root; + + // my quick&dirty iterator, should be replaced + SdFile getParentDir(const char *filepath, int *indx); +public: + // This needs to be called to set up the connection to the SD card + // before other methods are used. + boolean begin(uint8_t csPin = SD_CHIP_SELECT_PIN); + boolean begin(uint32_t clock, uint8_t csPin); + + // Open the specified file/directory with the supplied mode (e.g. read or + // write, etc). Returns a File object for interacting with the file. + // Note that currently only one file can be open at a time. + File open(const char *filename, uint8_t mode = FILE_READ); + File open(const String &filename, uint8_t mode = FILE_READ) { return open( filename.c_str(), mode ); } + + // Methods to determine if the requested file path exists. + boolean exists(const char *filepath); + boolean exists(const String &filepath) { return exists(filepath.c_str()); } + + // Create the requested directory heirarchy--if intermediate directories + // do not exist they will be created. + boolean mkdir(const char *filepath); + boolean mkdir(const String &filepath) { return mkdir(filepath.c_str()); } + + // Delete the file. + boolean remove(const char *filepath); + boolean remove(const String &filepath) { return remove(filepath.c_str()); } + + boolean rmdir(const char *filepath); + boolean rmdir(const String &filepath) { return rmdir(filepath.c_str()); } + +private: + + // This is used to determine the mode used to open a file + // it's here because it's the easiest place to pass the + // information through the directory walking function. But + // it's probably not the best place for it. + // It shouldn't be set directly--it is set via the parameters to `open`. + int fileOpenMode; + + friend class File; + friend boolean callback_openPath(SdFile&, const char *, boolean, void *); +}; + +extern SDClass SD; + +}; + +// We enclose File and SD classes in namespace SDLib to avoid conflicts +// with others legacy libraries that redefines File class. + +// This ensure compatibility with sketches that uses only SD library +using namespace SDLib; + +// This allows sketches to use SDLib::File with other libraries (in the +// sketch you must use SDFile instead of File to disambiguate) +typedef SDLib::File SDFile; +typedef SDLib::SDClass SDFileSystemClass; +#define SDFileSystem SDLib::SD + +#endif diff --git a/app/testdata/libraries/SD_1.1.1/SD/src/utility/FatStructs.h b/app/testdata/libraries/SD_1.1.1/SD/src/utility/FatStructs.h new file mode 100644 index 000000000..8a2d9ebcc --- /dev/null +++ b/app/testdata/libraries/SD_1.1.1/SD/src/utility/FatStructs.h @@ -0,0 +1,418 @@ +/* Arduino SdFat Library + * Copyright (C) 2009 by William Greiman + * + * This file is part of the Arduino SdFat 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 SdFat 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; +} __attribute__((packed)); +/** 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; +} __attribute__((packed)); +/** 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]; +} __attribute__((packed)); +/** 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; +} __attribute__((packed)); +//------------------------------------------------------------------------------ +// 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; +} __attribute__((packed)); +//------------------------------------------------------------------------------ +// 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/app/testdata/libraries/SD_1.1.1/SD/src/utility/Sd2Card.cpp b/app/testdata/libraries/SD_1.1.1/SD/src/utility/Sd2Card.cpp new file mode 100644 index 000000000..9ea413cde --- /dev/null +++ b/app/testdata/libraries/SD_1.1.1/SD/src/utility/Sd2Card.cpp @@ -0,0 +1,719 @@ +/* Arduino Sd2Card Library + * Copyright (C) 2009 by William Greiman + * + * This file is part of the Arduino Sd2Card 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 Sd2Card Library. If not, see + * . + */ +#define USE_SPI_LIB +#include +#include "Sd2Card.h" +//------------------------------------------------------------------------------ +#ifndef SOFTWARE_SPI +#ifdef USE_SPI_LIB + +#ifndef SDCARD_SPI +#define SDCARD_SPI SPI +#endif + +#include +static SPISettings settings; +#endif +// functions for hardware SPI +/** Send a byte to the card */ +static void spiSend(uint8_t b) { +#ifndef USE_SPI_LIB + SPDR = b; + while (!(SPSR & (1 << SPIF))) + ; +#else + SDCARD_SPI.transfer(b); +#endif +} +/** Receive a byte from the card */ +static uint8_t spiRec(void) { +#ifndef USE_SPI_LIB + spiSend(0XFF); + return SPDR; +#else + return SDCARD_SPI.transfer(0xFF); +#endif +} +#else // SOFTWARE_SPI +//------------------------------------------------------------------------------ +/** nop to tune soft SPI timing */ +#define nop asm volatile ("nop\n\t") +//------------------------------------------------------------------------------ +/** Soft SPI receive */ +uint8_t spiRec(void) { + uint8_t data = 0; + // no interrupts during byte receive - about 8 us + cli(); + // output pin high - like sending 0XFF + fastDigitalWrite(SPI_MOSI_PIN, HIGH); + + for (uint8_t i = 0; i < 8; i++) { + fastDigitalWrite(SPI_SCK_PIN, HIGH); + + // adjust so SCK is nice + nop; + nop; + + data <<= 1; + + if (fastDigitalRead(SPI_MISO_PIN)) data |= 1; + + fastDigitalWrite(SPI_SCK_PIN, LOW); + } + // enable interrupts + sei(); + return data; +} +//------------------------------------------------------------------------------ +/** Soft SPI send */ +void spiSend(uint8_t data) { + // no interrupts during byte send - about 8 us + cli(); + for (uint8_t i = 0; i < 8; i++) { + fastDigitalWrite(SPI_SCK_PIN, LOW); + + fastDigitalWrite(SPI_MOSI_PIN, data & 0X80); + + data <<= 1; + + fastDigitalWrite(SPI_SCK_PIN, HIGH); + } + // hold SCK high for a few ns + nop; + nop; + nop; + nop; + + fastDigitalWrite(SPI_SCK_PIN, LOW); + // enable interrupts + sei(); +} +#endif // SOFTWARE_SPI +//------------------------------------------------------------------------------ +// send command and return error code. Return zero for OK +uint8_t Sd2Card::cardCommand(uint8_t cmd, uint32_t arg) { + // end read if in partialBlockRead mode + readEnd(); + + // select card + chipSelectLow(); + + // wait up to 300 ms if busy + waitNotBusy(300); + + // send command + spiSend(cmd | 0x40); + + // send argument + for (int8_t s = 24; s >= 0; s -= 8) spiSend(arg >> s); + + // send CRC + uint8_t crc = 0XFF; + if (cmd == CMD0) crc = 0X95; // correct crc for CMD0 with arg 0 + if (cmd == CMD8) crc = 0X87; // correct crc for CMD8 with arg 0X1AA + spiSend(crc); + + // wait for response + for (uint8_t i = 0; ((status_ = spiRec()) & 0X80) && i != 0XFF; i++) + ; + return status_; +} +//------------------------------------------------------------------------------ +/** + * Determine the size of an SD flash memory card. + * + * \return The number of 512 byte data blocks in the card + * or zero if an error occurs. + */ +uint32_t Sd2Card::cardSize(void) { + csd_t csd; + if (!readCSD(&csd)) return 0; + if (csd.v1.csd_ver == 0) { + uint8_t read_bl_len = csd.v1.read_bl_len; + uint16_t c_size = (csd.v1.c_size_high << 10) + | (csd.v1.c_size_mid << 2) | csd.v1.c_size_low; + uint8_t c_size_mult = (csd.v1.c_size_mult_high << 1) + | csd.v1.c_size_mult_low; + return (uint32_t)(c_size + 1) << (c_size_mult + read_bl_len - 7); + } else if (csd.v2.csd_ver == 1) { + uint32_t c_size = ((uint32_t)csd.v2.c_size_high << 16) + | (csd.v2.c_size_mid << 8) | csd.v2.c_size_low; + return (c_size + 1) << 10; + } else { + error(SD_CARD_ERROR_BAD_CSD); + return 0; + } +} +//------------------------------------------------------------------------------ +static uint8_t chip_select_asserted = 0; + +void Sd2Card::chipSelectHigh(void) { + digitalWrite(chipSelectPin_, HIGH); +#ifdef USE_SPI_LIB + if (chip_select_asserted) { + chip_select_asserted = 0; + SDCARD_SPI.endTransaction(); + } +#endif +} +//------------------------------------------------------------------------------ +void Sd2Card::chipSelectLow(void) { +#ifdef USE_SPI_LIB + if (!chip_select_asserted) { + chip_select_asserted = 1; + SDCARD_SPI.beginTransaction(settings); + } +#endif + digitalWrite(chipSelectPin_, LOW); +} +//------------------------------------------------------------------------------ +/** Erase a range of blocks. + * + * \param[in] firstBlock The address of the first block in the range. + * \param[in] lastBlock The address of the last block in the range. + * + * \note This function requests the SD card to do a flash erase for a + * range of blocks. The data on the card after an erase operation is + * either 0 or 1, depends on the card vendor. The card must support + * single block erase. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +uint8_t Sd2Card::erase(uint32_t firstBlock, uint32_t lastBlock) { + if (!eraseSingleBlockEnable()) { + error(SD_CARD_ERROR_ERASE_SINGLE_BLOCK); + goto fail; + } + if (type_ != SD_CARD_TYPE_SDHC) { + firstBlock <<= 9; + lastBlock <<= 9; + } + if (cardCommand(CMD32, firstBlock) + || cardCommand(CMD33, lastBlock) + || cardCommand(CMD38, 0)) { + error(SD_CARD_ERROR_ERASE); + goto fail; + } + if (!waitNotBusy(SD_ERASE_TIMEOUT)) { + error(SD_CARD_ERROR_ERASE_TIMEOUT); + goto fail; + } + chipSelectHigh(); + return true; + + fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** Determine if card supports single block erase. + * + * \return The value one, true, is returned if single block erase is supported. + * The value zero, false, is returned if single block erase is not supported. + */ +uint8_t Sd2Card::eraseSingleBlockEnable(void) { + csd_t csd; + return readCSD(&csd) ? csd.v1.erase_blk_en : 0; +} +//------------------------------------------------------------------------------ +/** + * Initialize an SD flash memory card. + * + * \param[in] sckRateID SPI clock rate selector. See setSckRate(). + * \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. The reason for failure + * can be determined by calling errorCode() and errorData(). + */ +uint8_t Sd2Card::init(uint8_t sckRateID, uint8_t chipSelectPin) { + errorCode_ = inBlock_ = partialBlockRead_ = type_ = 0; + chipSelectPin_ = chipSelectPin; + // 16-bit init start time allows over a minute + uint16_t t0 = (uint16_t)millis(); + uint32_t arg; + + // set pin modes + pinMode(chipSelectPin_, OUTPUT); + digitalWrite(chipSelectPin_, HIGH); +#ifndef USE_SPI_LIB + pinMode(SPI_MISO_PIN, INPUT); + pinMode(SPI_MOSI_PIN, OUTPUT); + pinMode(SPI_SCK_PIN, OUTPUT); +#endif + +#ifndef SOFTWARE_SPI +#ifndef USE_SPI_LIB + // SS must be in output mode even it is not chip select + pinMode(SS_PIN, OUTPUT); + digitalWrite(SS_PIN, HIGH); // disable any SPI device using hardware SS pin + // Enable SPI, Master, clock rate f_osc/128 + SPCR = (1 << SPE) | (1 << MSTR) | (1 << SPR1) | (1 << SPR0); + // clear double speed + SPSR &= ~(1 << SPI2X); +#else // USE_SPI_LIB + SDCARD_SPI.begin(); + settings = SPISettings(250000, MSBFIRST, SPI_MODE0); +#endif // USE_SPI_LIB +#endif // SOFTWARE_SPI + + // must supply min of 74 clock cycles with CS high. +#ifdef USE_SPI_LIB + SDCARD_SPI.beginTransaction(settings); +#endif + for (uint8_t i = 0; i < 10; i++) spiSend(0XFF); +#ifdef USE_SPI_LIB + SDCARD_SPI.endTransaction(); +#endif + + chipSelectLow(); + + // command to go idle in SPI mode + while ((status_ = cardCommand(CMD0, 0)) != R1_IDLE_STATE) { + if (((uint16_t)(millis() - t0)) > SD_INIT_TIMEOUT) { + error(SD_CARD_ERROR_CMD0); + goto fail; + } + } + // check SD version + if ((cardCommand(CMD8, 0x1AA) & R1_ILLEGAL_COMMAND)) { + type(SD_CARD_TYPE_SD1); + } else { + // only need last byte of r7 response + for (uint8_t i = 0; i < 4; i++) status_ = spiRec(); + if (status_ != 0XAA) { + error(SD_CARD_ERROR_CMD8); + goto fail; + } + type(SD_CARD_TYPE_SD2); + } + // initialize card and send host supports SDHC if SD2 + arg = type() == SD_CARD_TYPE_SD2 ? 0X40000000 : 0; + + while ((status_ = cardAcmd(ACMD41, arg)) != R1_READY_STATE) { + // check for timeout + if (((uint16_t)(millis() - t0)) > SD_INIT_TIMEOUT) { + error(SD_CARD_ERROR_ACMD41); + goto fail; + } + } + // if SD2 read OCR register to check for SDHC card + if (type() == SD_CARD_TYPE_SD2) { + if (cardCommand(CMD58, 0)) { + error(SD_CARD_ERROR_CMD58); + goto fail; + } + if ((spiRec() & 0XC0) == 0XC0) type(SD_CARD_TYPE_SDHC); + // discard rest of ocr - contains allowed voltage range + for (uint8_t i = 0; i < 3; i++) spiRec(); + } + chipSelectHigh(); + +#ifndef SOFTWARE_SPI + return setSckRate(sckRateID); +#else // SOFTWARE_SPI + return true; +#endif // SOFTWARE_SPI + + fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** + * Enable or disable partial block reads. + * + * Enabling partial block reads improves performance by allowing a block + * to be read over the SPI bus as several sub-blocks. Errors may occur + * if the time between reads is too long since the SD card may timeout. + * The SPI SS line will be held low until the entire block is read or + * readEnd() is called. + * + * Use this for applications like the Adafruit Wave Shield. + * + * \param[in] value The value TRUE (non-zero) or FALSE (zero).) + */ +void Sd2Card::partialBlockRead(uint8_t value) { + readEnd(); + partialBlockRead_ = value; +} +//------------------------------------------------------------------------------ +/** + * Read a 512 byte block from an SD card device. + * + * \param[in] block 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 Sd2Card::readBlock(uint32_t block, uint8_t* dst) { + return readData(block, 0, 512, dst); +} +//------------------------------------------------------------------------------ +/** + * Read part of a 512 byte block from an SD card. + * + * \param[in] block Logical block to be read. + * \param[in] offset Number of bytes to skip at start of block + * \param[out] dst Pointer to the location that will receive the data. + * \param[in] count Number of bytes to read + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +uint8_t Sd2Card::readData(uint32_t block, + uint16_t offset, uint16_t count, uint8_t* dst) { + if (count == 0) return true; + if ((count + offset) > 512) { + goto fail; + } + if (!inBlock_ || block != block_ || offset < offset_) { + block_ = block; + // use address if not SDHC card + if (type()!= SD_CARD_TYPE_SDHC) block <<= 9; + if (cardCommand(CMD17, block)) { + error(SD_CARD_ERROR_CMD17); + goto fail; + } + if (!waitStartBlock()) { + goto fail; + } + offset_ = 0; + inBlock_ = 1; + } + +#ifdef OPTIMIZE_HARDWARE_SPI + // start first spi transfer + SPDR = 0XFF; + + // skip data before offset + for (;offset_ < offset; offset_++) { + while (!(SPSR & (1 << SPIF))) + ; + SPDR = 0XFF; + } + // transfer data + n = count - 1; + for (uint16_t i = 0; i < n; i++) { + while (!(SPSR & (1 << SPIF))) + ; + dst[i] = SPDR; + SPDR = 0XFF; + } + // wait for last byte + while (!(SPSR & (1 << SPIF))) + ; + dst[n] = SPDR; + +#else // OPTIMIZE_HARDWARE_SPI + + // skip data before offset + for (;offset_ < offset; offset_++) { + spiRec(); + } + // transfer data + for (uint16_t i = 0; i < count; i++) { + dst[i] = spiRec(); + } +#endif // OPTIMIZE_HARDWARE_SPI + + offset_ += count; + if (!partialBlockRead_ || offset_ >= 512) { + // read rest of data, checksum and set chip select high + readEnd(); + } + return true; + + fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** Skip remaining data in a block when in partial block read mode. */ +void Sd2Card::readEnd(void) { + if (inBlock_) { + // skip data and crc +#ifdef OPTIMIZE_HARDWARE_SPI + // optimize skip for hardware + SPDR = 0XFF; + while (offset_++ < 513) { + while (!(SPSR & (1 << SPIF))) + ; + SPDR = 0XFF; + } + // wait for last crc byte + while (!(SPSR & (1 << SPIF))) + ; +#else // OPTIMIZE_HARDWARE_SPI + while (offset_++ < 514) spiRec(); +#endif // OPTIMIZE_HARDWARE_SPI + chipSelectHigh(); + inBlock_ = 0; + } +} +//------------------------------------------------------------------------------ +/** read CID or CSR register */ +uint8_t Sd2Card::readRegister(uint8_t cmd, void* buf) { + uint8_t* dst = reinterpret_cast(buf); + if (cardCommand(cmd, 0)) { + error(SD_CARD_ERROR_READ_REG); + goto fail; + } + if (!waitStartBlock()) goto fail; + // transfer data + for (uint16_t i = 0; i < 16; i++) dst[i] = spiRec(); + spiRec(); // get first crc byte + spiRec(); // get second crc byte + chipSelectHigh(); + return true; + + fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** + * Set the SPI clock rate. + * + * \param[in] sckRateID A value in the range [0, 6]. + * + * The SPI clock will be set to F_CPU/pow(2, 1 + sckRateID). The maximum + * SPI rate is F_CPU/2 for \a sckRateID = 0 and the minimum rate is F_CPU/128 + * for \a scsRateID = 6. + * + * \return The value one, true, is returned for success and the value zero, + * false, is returned for an invalid value of \a sckRateID. + */ +uint8_t Sd2Card::setSckRate(uint8_t sckRateID) { + if (sckRateID > 6) { + error(SD_CARD_ERROR_SCK_RATE); + return false; + } +#ifndef USE_SPI_LIB + // see avr processor datasheet for SPI register bit definitions + if ((sckRateID & 1) || sckRateID == 6) { + SPSR &= ~(1 << SPI2X); + } else { + SPSR |= (1 << SPI2X); + } + SPCR &= ~((1 < SD_READ_TIMEOUT) { + error(SD_CARD_ERROR_READ_TIMEOUT); + goto fail; + } + } + if (status_ != DATA_START_BLOCK) { + error(SD_CARD_ERROR_READ); + goto fail; + } + return true; + + fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** + * Writes a 512 byte block to an SD card. + * + * \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 Sd2Card::writeBlock(uint32_t blockNumber, const uint8_t* src) { +#if SD_PROTECT_BLOCK_ZERO + // don't allow write to first block + if (blockNumber == 0) { + error(SD_CARD_ERROR_WRITE_BLOCK_ZERO); + goto fail; + } +#endif // SD_PROTECT_BLOCK_ZERO + + // use address if not SDHC card + if (type() != SD_CARD_TYPE_SDHC) blockNumber <<= 9; + if (cardCommand(CMD24, blockNumber)) { + error(SD_CARD_ERROR_CMD24); + goto fail; + } + if (!writeData(DATA_START_BLOCK, src)) goto fail; + + // wait for flash programming to complete + if (!waitNotBusy(SD_WRITE_TIMEOUT)) { + error(SD_CARD_ERROR_WRITE_TIMEOUT); + goto fail; + } + // response is r2 so get and check two bytes for nonzero + if (cardCommand(CMD13, 0) || spiRec()) { + error(SD_CARD_ERROR_WRITE_PROGRAMMING); + goto fail; + } + chipSelectHigh(); + return true; + + fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** Write one data block in a multiple block write sequence */ +uint8_t Sd2Card::writeData(const uint8_t* src) { + // wait for previous write to finish + if (!waitNotBusy(SD_WRITE_TIMEOUT)) { + error(SD_CARD_ERROR_WRITE_MULTIPLE); + chipSelectHigh(); + return false; + } + return writeData(WRITE_MULTIPLE_TOKEN, src); +} +//------------------------------------------------------------------------------ +// send one block of data for write block or write multiple blocks +uint8_t Sd2Card::writeData(uint8_t token, const uint8_t* src) { +#ifdef OPTIMIZE_HARDWARE_SPI + + // send data - optimized loop + SPDR = token; + + // send two byte per iteration + for (uint16_t i = 0; i < 512; i += 2) { + while (!(SPSR & (1 << SPIF))) + ; + SPDR = src[i]; + while (!(SPSR & (1 << SPIF))) + ; + SPDR = src[i+1]; + } + + // wait for last data byte + while (!(SPSR & (1 << SPIF))) + ; + +#else // OPTIMIZE_HARDWARE_SPI + spiSend(token); + for (uint16_t i = 0; i < 512; i++) { + spiSend(src[i]); + } +#endif // OPTIMIZE_HARDWARE_SPI + spiSend(0xff); // dummy crc + spiSend(0xff); // dummy crc + + status_ = spiRec(); + if ((status_ & DATA_RES_MASK) != DATA_RES_ACCEPTED) { + error(SD_CARD_ERROR_WRITE); + chipSelectHigh(); + return false; + } + return true; +} +//------------------------------------------------------------------------------ +/** Start a write multiple blocks sequence. + * + * \param[in] blockNumber Address of first block in sequence. + * \param[in] eraseCount The number of blocks to be pre-erased. + * + * \note This function is used with writeData() and writeStop() + * for optimized multiple block writes. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +uint8_t Sd2Card::writeStart(uint32_t blockNumber, uint32_t eraseCount) { +#if SD_PROTECT_BLOCK_ZERO + // don't allow write to first block + if (blockNumber == 0) { + error(SD_CARD_ERROR_WRITE_BLOCK_ZERO); + goto fail; + } +#endif // SD_PROTECT_BLOCK_ZERO + // send pre-erase count + if (cardAcmd(ACMD23, eraseCount)) { + error(SD_CARD_ERROR_ACMD23); + goto fail; + } + // use address if not SDHC card + if (type() != SD_CARD_TYPE_SDHC) blockNumber <<= 9; + if (cardCommand(CMD25, blockNumber)) { + error(SD_CARD_ERROR_CMD25); + goto fail; + } + return true; + + fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** End a write multiple blocks sequence. + * +* \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +uint8_t Sd2Card::writeStop(void) { + if (!waitNotBusy(SD_WRITE_TIMEOUT)) goto fail; + spiSend(STOP_TRAN_TOKEN); + if (!waitNotBusy(SD_WRITE_TIMEOUT)) goto fail; + chipSelectHigh(); + return true; + + fail: + error(SD_CARD_ERROR_STOP_TRAN); + chipSelectHigh(); + return false; +} diff --git a/app/testdata/libraries/SD_1.1.1/SD/src/utility/Sd2Card.h b/app/testdata/libraries/SD_1.1.1/SD/src/utility/Sd2Card.h new file mode 100644 index 000000000..bcb809470 --- /dev/null +++ b/app/testdata/libraries/SD_1.1.1/SD/src/utility/Sd2Card.h @@ -0,0 +1,260 @@ +/* Arduino Sd2Card Library + * Copyright (C) 2009 by William Greiman + * + * This file is part of the Arduino Sd2Card 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 Sd2Card Library. If not, see + * . + */ +#ifndef Sd2Card_h +#define Sd2Card_h +/** + * \file + * Sd2Card class + */ +#include "Sd2PinMap.h" +#include "SdInfo.h" +/** Set SCK to max rate of F_CPU/2. See Sd2Card::setSckRate(). */ +uint8_t const SPI_FULL_SPEED = 0; +/** Set SCK rate to F_CPU/4. See Sd2Card::setSckRate(). */ +uint8_t const SPI_HALF_SPEED = 1; +/** Set SCK rate to F_CPU/8. Sd2Card::setSckRate(). */ +uint8_t const SPI_QUARTER_SPEED = 2; +/** + * USE_SPI_LIB: if set, use the SPI library bundled with Arduino IDE, otherwise + * run with a standalone driver for AVR. + */ +#define USE_SPI_LIB +/** + * Define MEGA_SOFT_SPI non-zero to use software SPI on Mega Arduinos. + * Pins used are SS 10, MOSI 11, MISO 12, and SCK 13. + * + * MEGA_SOFT_SPI allows an unmodified Adafruit GPS Shield to be used + * on Mega Arduinos. Software SPI works well with GPS Shield V1.1 + * but many SD cards will fail with GPS Shield V1.0. + */ +#define MEGA_SOFT_SPI 0 +//------------------------------------------------------------------------------ +#if MEGA_SOFT_SPI && (defined(__AVR_ATmega1280__)||defined(__AVR_ATmega2560__)) +#define SOFTWARE_SPI +#endif // MEGA_SOFT_SPI +//------------------------------------------------------------------------------ +// SPI pin definitions +// +#ifndef SOFTWARE_SPI +// hardware pin defs + +// include pins_arduino.h or variant.h depending on architecture, via Arduino.h +#include + +/** + * SD Chip Select pin + * + * Warning if this pin is redefined the hardware SS will 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. + */ +#ifndef SDCARD_SS_PIN +/** The default chip select pin for the SD card is SS. */ +uint8_t const SD_CHIP_SELECT_PIN = SS; +#else +uint8_t const SD_CHIP_SELECT_PIN = SDCARD_SS_PIN; +#endif + +// The following three pins must not be redefined for hardware SPI, +// so ensure that they are taken from pins_arduino.h or variant.h, depending on architecture. +#ifndef SDCARD_MOSI_PIN +/** SPI Master Out Slave In pin */ +uint8_t const SPI_MOSI_PIN = MOSI; +/** SPI Master In Slave Out pin */ +uint8_t const SPI_MISO_PIN = MISO; +/** SPI Clock pin */ +uint8_t const SPI_SCK_PIN = SCK; +#else +uint8_t const SPI_MOSI_PIN = SDCARD_MOSI_PIN; +uint8_t const SPI_MISO_PIN = SDCARD_MISO_PIN; +uint8_t const SPI_SCK_PIN = SDCARD_SCK_PIN; +#endif + +/** optimize loops for hardware SPI */ +#ifndef USE_SPI_LIB +#define OPTIMIZE_HARDWARE_SPI +#endif + +#else // SOFTWARE_SPI +// define software SPI pins so Mega can use unmodified GPS Shield +/** SPI chip select pin */ +uint8_t const SD_CHIP_SELECT_PIN = 10; +/** SPI Master Out Slave In pin */ +uint8_t const SPI_MOSI_PIN = 11; +/** SPI Master In Slave Out pin */ +uint8_t const SPI_MISO_PIN = 12; +/** SPI Clock pin */ +uint8_t const SPI_SCK_PIN = 13; +#endif // SOFTWARE_SPI +//------------------------------------------------------------------------------ +/** Protect block zero from write if nonzero */ +#define SD_PROTECT_BLOCK_ZERO 1 +/** init timeout ms */ +uint16_t const SD_INIT_TIMEOUT = 2000; +/** erase timeout ms */ +uint16_t const SD_ERASE_TIMEOUT = 10000; +/** read timeout ms */ +uint16_t const SD_READ_TIMEOUT = 300; +/** write time out ms */ +uint16_t const SD_WRITE_TIMEOUT = 600; +//------------------------------------------------------------------------------ +// SD card errors +/** timeout error for command CMD0 */ +uint8_t const SD_CARD_ERROR_CMD0 = 0X1; +/** CMD8 was not accepted - not a valid SD card*/ +uint8_t const SD_CARD_ERROR_CMD8 = 0X2; +/** card returned an error response for CMD17 (read block) */ +uint8_t const SD_CARD_ERROR_CMD17 = 0X3; +/** card returned an error response for CMD24 (write block) */ +uint8_t const SD_CARD_ERROR_CMD24 = 0X4; +/** WRITE_MULTIPLE_BLOCKS command failed */ +uint8_t const SD_CARD_ERROR_CMD25 = 0X05; +/** card returned an error response for CMD58 (read OCR) */ +uint8_t const SD_CARD_ERROR_CMD58 = 0X06; +/** SET_WR_BLK_ERASE_COUNT failed */ +uint8_t const SD_CARD_ERROR_ACMD23 = 0X07; +/** card's ACMD41 initialization process timeout */ +uint8_t const SD_CARD_ERROR_ACMD41 = 0X08; +/** card returned a bad CSR version field */ +uint8_t const SD_CARD_ERROR_BAD_CSD = 0X09; +/** erase block group command failed */ +uint8_t const SD_CARD_ERROR_ERASE = 0X0A; +/** card not capable of single block erase */ +uint8_t const SD_CARD_ERROR_ERASE_SINGLE_BLOCK = 0X0B; +/** Erase sequence timed out */ +uint8_t const SD_CARD_ERROR_ERASE_TIMEOUT = 0X0C; +/** card returned an error token instead of read data */ +uint8_t const SD_CARD_ERROR_READ = 0X0D; +/** read CID or CSD failed */ +uint8_t const SD_CARD_ERROR_READ_REG = 0X0E; +/** timeout while waiting for start of read data */ +uint8_t const SD_CARD_ERROR_READ_TIMEOUT = 0X0F; +/** card did not accept STOP_TRAN_TOKEN */ +uint8_t const SD_CARD_ERROR_STOP_TRAN = 0X10; +/** card returned an error token as a response to a write operation */ +uint8_t const SD_CARD_ERROR_WRITE = 0X11; +/** attempt to write protected block zero */ +uint8_t const SD_CARD_ERROR_WRITE_BLOCK_ZERO = 0X12; +/** card did not go ready for a multiple block write */ +uint8_t const SD_CARD_ERROR_WRITE_MULTIPLE = 0X13; +/** card returned an error to a CMD13 status check after a write */ +uint8_t const SD_CARD_ERROR_WRITE_PROGRAMMING = 0X14; +/** timeout occurred during write programming */ +uint8_t const SD_CARD_ERROR_WRITE_TIMEOUT = 0X15; +/** incorrect rate selected */ +uint8_t const SD_CARD_ERROR_SCK_RATE = 0X16; +//------------------------------------------------------------------------------ +// card types +/** Standard capacity V1 SD card */ +uint8_t const SD_CARD_TYPE_SD1 = 1; +/** Standard capacity V2 SD card */ +uint8_t const SD_CARD_TYPE_SD2 = 2; +/** High Capacity SD card */ +uint8_t const SD_CARD_TYPE_SDHC = 3; +//------------------------------------------------------------------------------ +/** + * \class Sd2Card + * \brief Raw access to SD and SDHC flash memory cards. + */ +class Sd2Card { + public: + /** Construct an instance of Sd2Card. */ + Sd2Card(void) : errorCode_(0), inBlock_(0), partialBlockRead_(0), type_(0) {} + uint32_t cardSize(void); + uint8_t erase(uint32_t firstBlock, uint32_t lastBlock); + uint8_t eraseSingleBlockEnable(void); + /** + * \return error code for last error. See Sd2Card.h for a list of error codes. + */ + uint8_t errorCode(void) const {return errorCode_;} + /** \return error data for last error. */ + uint8_t errorData(void) const {return status_;} + /** + * Initialize an SD flash memory card with default clock rate and chip + * select pin. See sd2Card::init(uint8_t sckRateID, uint8_t chipSelectPin). + */ + uint8_t init(void) { + return init(SPI_FULL_SPEED, SD_CHIP_SELECT_PIN); + } + /** + * Initialize an SD flash memory card with the selected SPI clock rate + * and the default SD chip select pin. + * See sd2Card::init(uint8_t sckRateID, uint8_t chipSelectPin). + */ + uint8_t init(uint8_t sckRateID) { + return init(sckRateID, SD_CHIP_SELECT_PIN); + } + uint8_t init(uint8_t sckRateID, uint8_t chipSelectPin); + void partialBlockRead(uint8_t value); + /** Returns the current value, true or false, for partial block read. */ + uint8_t partialBlockRead(void) const {return partialBlockRead_;} + uint8_t readBlock(uint32_t block, uint8_t* dst); + uint8_t readData(uint32_t block, + uint16_t offset, uint16_t count, uint8_t* dst); + /** + * Read a cards CID register. The CID contains card identification + * information such as Manufacturer ID, Product name, Product serial + * number and Manufacturing date. */ + uint8_t readCID(cid_t* cid) { + return readRegister(CMD10, cid); + } + /** + * Read a cards CSD register. The CSD contains Card-Specific Data that + * provides information regarding access to the card's contents. */ + uint8_t readCSD(csd_t* csd) { + return readRegister(CMD9, csd); + } + void readEnd(void); + uint8_t setSckRate(uint8_t sckRateID); +#ifdef USE_SPI_LIB + uint8_t setSpiClock(uint32_t clock); +#endif + /** Return the card type: SD V1, SD V2 or SDHC */ + uint8_t type(void) const {return type_;} + uint8_t writeBlock(uint32_t blockNumber, const uint8_t* src); + uint8_t writeData(const uint8_t* src); + uint8_t writeStart(uint32_t blockNumber, uint32_t eraseCount); + uint8_t writeStop(void); + private: + uint32_t block_; + uint8_t chipSelectPin_; + uint8_t errorCode_; + uint8_t inBlock_; + uint16_t offset_; + uint8_t partialBlockRead_; + uint8_t status_; + uint8_t type_; + // private functions + uint8_t cardAcmd(uint8_t cmd, uint32_t arg) { + cardCommand(CMD55, 0); + return cardCommand(cmd, arg); + } + uint8_t cardCommand(uint8_t cmd, uint32_t arg); + void error(uint8_t code) {errorCode_ = code;} + uint8_t readRegister(uint8_t cmd, void* buf); + uint8_t sendWriteCommand(uint32_t blockNumber, uint32_t eraseCount); + void chipSelectHigh(void); + void chipSelectLow(void); + void type(uint8_t value) {type_ = value;} + uint8_t waitNotBusy(uint16_t timeoutMillis); + uint8_t writeData(uint8_t token, const uint8_t* src); + uint8_t waitStartBlock(void); +}; +#endif // Sd2Card_h diff --git a/app/testdata/libraries/SD_1.1.1/SD/src/utility/Sd2PinMap.h b/app/testdata/libraries/SD_1.1.1/SD/src/utility/Sd2PinMap.h new file mode 100644 index 000000000..3e2df439a --- /dev/null +++ b/app/testdata/libraries/SD_1.1.1/SD/src/utility/Sd2PinMap.h @@ -0,0 +1,511 @@ +/* Arduino SdFat Library + * Copyright (C) 2010 by William Greiman + * + * This file is part of the Arduino SdFat 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 SdFat Library. If not, see + * . + */ +#if defined(__arm__) // Arduino Due Board follows + +#ifndef Sd2PinMap_h +#define Sd2PinMap_h + +#include + +uint8_t const SS_PIN = SS; +uint8_t const MOSI_PIN = MOSI; +uint8_t const MISO_PIN = MISO; +uint8_t const SCK_PIN = SCK; + +#endif // Sd2PinMap_h + +#elif defined(__AVR__) // Other AVR based Boards follows + +// Warning this file was generated by a program. +#ifndef Sd2PinMap_h +#define Sd2PinMap_h +#include + +//------------------------------------------------------------------------------ +/** struct for mapping digital pins */ +struct pin_map_t { + volatile uint8_t* ddr; + volatile uint8_t* pin; + volatile uint8_t* port; + uint8_t bit; +}; +//------------------------------------------------------------------------------ +#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) +// Mega + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 20; +uint8_t const SCL_PIN = 21; + +// SPI port +uint8_t const SS_PIN = 53; +uint8_t const MOSI_PIN = 51; +uint8_t const MISO_PIN = 50; +uint8_t const SCK_PIN = 52; + +static const pin_map_t digitalPinMap[] = { + {&DDRE, &PINE, &PORTE, 0}, // E0 0 + {&DDRE, &PINE, &PORTE, 1}, // E1 1 + {&DDRE, &PINE, &PORTE, 4}, // E4 2 + {&DDRE, &PINE, &PORTE, 5}, // E5 3 + {&DDRG, &PING, &PORTG, 5}, // G5 4 + {&DDRE, &PINE, &PORTE, 3}, // E3 5 + {&DDRH, &PINH, &PORTH, 3}, // H3 6 + {&DDRH, &PINH, &PORTH, 4}, // H4 7 + {&DDRH, &PINH, &PORTH, 5}, // H5 8 + {&DDRH, &PINH, &PORTH, 6}, // H6 9 + {&DDRB, &PINB, &PORTB, 4}, // B4 10 + {&DDRB, &PINB, &PORTB, 5}, // B5 11 + {&DDRB, &PINB, &PORTB, 6}, // B6 12 + {&DDRB, &PINB, &PORTB, 7}, // B7 13 + {&DDRJ, &PINJ, &PORTJ, 1}, // J1 14 + {&DDRJ, &PINJ, &PORTJ, 0}, // J0 15 + {&DDRH, &PINH, &PORTH, 1}, // H1 16 + {&DDRH, &PINH, &PORTH, 0}, // H0 17 + {&DDRD, &PIND, &PORTD, 3}, // D3 18 + {&DDRD, &PIND, &PORTD, 2}, // D2 19 + {&DDRD, &PIND, &PORTD, 1}, // D1 20 + {&DDRD, &PIND, &PORTD, 0}, // D0 21 + {&DDRA, &PINA, &PORTA, 0}, // A0 22 + {&DDRA, &PINA, &PORTA, 1}, // A1 23 + {&DDRA, &PINA, &PORTA, 2}, // A2 24 + {&DDRA, &PINA, &PORTA, 3}, // A3 25 + {&DDRA, &PINA, &PORTA, 4}, // A4 26 + {&DDRA, &PINA, &PORTA, 5}, // A5 27 + {&DDRA, &PINA, &PORTA, 6}, // A6 28 + {&DDRA, &PINA, &PORTA, 7}, // A7 29 + {&DDRC, &PINC, &PORTC, 7}, // C7 30 + {&DDRC, &PINC, &PORTC, 6}, // C6 31 + {&DDRC, &PINC, &PORTC, 5}, // C5 32 + {&DDRC, &PINC, &PORTC, 4}, // C4 33 + {&DDRC, &PINC, &PORTC, 3}, // C3 34 + {&DDRC, &PINC, &PORTC, 2}, // C2 35 + {&DDRC, &PINC, &PORTC, 1}, // C1 36 + {&DDRC, &PINC, &PORTC, 0}, // C0 37 + {&DDRD, &PIND, &PORTD, 7}, // D7 38 + {&DDRG, &PING, &PORTG, 2}, // G2 39 + {&DDRG, &PING, &PORTG, 1}, // G1 40 + {&DDRG, &PING, &PORTG, 0}, // G0 41 + {&DDRL, &PINL, &PORTL, 7}, // L7 42 + {&DDRL, &PINL, &PORTL, 6}, // L6 43 + {&DDRL, &PINL, &PORTL, 5}, // L5 44 + {&DDRL, &PINL, &PORTL, 4}, // L4 45 + {&DDRL, &PINL, &PORTL, 3}, // L3 46 + {&DDRL, &PINL, &PORTL, 2}, // L2 47 + {&DDRL, &PINL, &PORTL, 1}, // L1 48 + {&DDRL, &PINL, &PORTL, 0}, // L0 49 + {&DDRB, &PINB, &PORTB, 3}, // B3 50 + {&DDRB, &PINB, &PORTB, 2}, // B2 51 + {&DDRB, &PINB, &PORTB, 1}, // B1 52 + {&DDRB, &PINB, &PORTB, 0}, // B0 53 + {&DDRF, &PINF, &PORTF, 0}, // F0 54 + {&DDRF, &PINF, &PORTF, 1}, // F1 55 + {&DDRF, &PINF, &PORTF, 2}, // F2 56 + {&DDRF, &PINF, &PORTF, 3}, // F3 57 + {&DDRF, &PINF, &PORTF, 4}, // F4 58 + {&DDRF, &PINF, &PORTF, 5}, // F5 59 + {&DDRF, &PINF, &PORTF, 6}, // F6 60 + {&DDRF, &PINF, &PORTF, 7}, // F7 61 + {&DDRK, &PINK, &PORTK, 0}, // K0 62 + {&DDRK, &PINK, &PORTK, 1}, // K1 63 + {&DDRK, &PINK, &PORTK, 2}, // K2 64 + {&DDRK, &PINK, &PORTK, 3}, // K3 65 + {&DDRK, &PINK, &PORTK, 4}, // K4 66 + {&DDRK, &PINK, &PORTK, 5}, // K5 67 + {&DDRK, &PINK, &PORTK, 6}, // K6 68 + {&DDRK, &PINK, &PORTK, 7} // K7 69 +}; +//------------------------------------------------------------------------------ +#elif (defined(__AVR_ATmega644P__) || defined(__AVR_ATmega1284P__)) && defined(CORE_MICRODUINO) +// Microduino Core+ + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 20; +uint8_t const SCL_PIN = 21; + +// SPI port +uint8_t const SS_PIN = 10; +uint8_t const MOSI_PIN = 11; +uint8_t const MISO_PIN = 12; +uint8_t const SCK_PIN = 13; + +static const pin_map_t digitalPinMap[] = { + {&DDRD, &PIND, &PORTD, 0}, // D0 PD0 + {&DDRD, &PIND, &PORTD, 1}, // D1 PD1 + {&DDRD, &PIND, &PORTD, 2}, // D2 PD2 + {&DDRD, &PIND, &PORTD, 3}, // D3 PD3 + {&DDRB, &PINB, &PORTB, 0}, // D4 PB0 + {&DDRB, &PINB, &PORTB, 1}, // D5 PB1 + {&DDRB, &PINB, &PORTB, 2}, // D6 PB2 + {&DDRB, &PINB, &PORTB, 3}, // D7 PB3 + {&DDRD, &PIND, &PORTD, 6}, // D8 PD6 + {&DDRD, &PIND, &PORTD, 5}, // D9 PD5 + {&DDRB, &PINB, &PORTB, 4}, // D10 PB4 + {&DDRB, &PINB, &PORTB, 5}, // D11 PB5 + {&DDRB, &PINB, &PORTB, 6}, // D12 PB6 + {&DDRB, &PINB, &PORTB, 7}, // D13 PB7 + {&DDRC, &PINC, &PORTC, 7}, // D14 PC7 + {&DDRC, &PINC, &PORTC, 6}, // D15 PC6 + {&DDRC, &PINC, &PORTC, 5}, // D16 PC5 + {&DDRC, &PINC, &PORTC, 4}, // D17 PC4 + {&DDRC, &PINC, &PORTC, 3}, // D18 PC3 + {&DDRC, &PINC, &PORTC, 2}, // D19 PC2 + {&DDRC, &PINC, &PORTC, 1}, // D20 PC1 + {&DDRC, &PINC, &PORTC, 0}, // D21 PC0 + {&DDRD, &PIND, &PORTD, 4}, // D22 PD4 + {&DDRD, &PIND, &PORTD, 7}, // D23 PD7 + {&DDRA, &PINA, &PORTA, 7}, // D24 PA7 + {&DDRA, &PINA, &PORTA, 6}, // D25 PA6 + {&DDRA, &PINA, &PORTA, 5}, // D26 PA5 + {&DDRA, &PINA, &PORTA, 4}, // D27 PA4 + {&DDRA, &PINA, &PORTA, 3}, // D28 PA3 + {&DDRA, &PINA, &PORTA, 2}, // D29 PA2 + {&DDRA, &PINA, &PORTA, 1}, // D30 PA1 + {&DDRA, &PINA, &PORTA, 0} // D31 PA0 +}; +//------------------------------------------------------------------------------ +#elif defined(__AVR_ATmega128RFA1__) && defined(CORE_MICRODUINO) +// Microduino Core RF + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 18; +uint8_t const SCL_PIN = 19; + +// SPI port +uint8_t const SS_PIN = 10; +uint8_t const MOSI_PIN = 11; +uint8_t const MISO_PIN = 12; +uint8_t const SCK_PIN = 13; + +static const pin_map_t digitalPinMap[] = { + {&DDRD, &PINE, &PORTE, 0}, // D0 PE0 + {&DDRD, &PINE, &PORTE, 1}, // D1 PE1 + {&DDRD, &PIND, &PORTD, 2}, // D2 PD2 + {&DDRD, &PIND, &PORTD, 3}, // D3 PD3 + {&DDRB, &PINE, &PORTE, 3}, // D4 PE3 + {&DDRB, &PINE, &PORTE, 4}, // D5 PE4 + {&DDRB, &PINE, &PORTE, 5}, // D6 PE5 + {&DDRB, &PINB, &PORTB, 7}, // D7 PB7 + {&DDRD, &PINB, &PORTB, 6}, // D8 PB6 + {&DDRD, &PINB, &PORTB, 5}, // D9 PB5 + {&DDRB, &PINB, &PORTB, 4}, // D10 PB4 + {&DDRB, &PINB, &PORTB, 2}, // D11 PB2 + {&DDRB, &PINB, &PORTB, 3}, // D12 PB3 + {&DDRB, &PINB, &PORTB, 1}, // D13 PB1 + {&DDRF, &PINF, &PORTF, 7}, // D14 PF7 + {&DDRF, &PINF, &PORTF, 6}, // D15 PF6 + {&DDRF, &PINF, &PORTF, 5}, // D16 PF5 + {&DDRF, &PINF, &PORTF, 4}, // D17 PF4 + {&DDRD, &PIND, &PORTD, 1}, // D18 PD1 + {&DDRD, &PIND, &PORTD, 0}, // D19 PD0 + {&DDRF, &PINF, &PORTF, 3}, // D20 PF3 + {&DDRF, &PINF, &PORTF, 2}, // D21 PF2 +}; +//------------------------------------------------------------------------------ +#elif defined(__AVR_ATmega32U4__) && defined(CORE_MICRODUINO) +// Microduino Core USB + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 18; +uint8_t const SCL_PIN = 19; + +// SPI port +uint8_t const SS_PIN = 10; +uint8_t const MOSI_PIN = 11; +uint8_t const MISO_PIN = 12; +uint8_t const SCK_PIN = 13; + +static const pin_map_t digitalPinMap[] = { + {&DDRD, &PIND, &PORTD, 2}, // D0 - PD2 + {&DDRD, &PIND, &PORTD, 3}, // D1 - PD3 + {&DDRE, &PINE, &PORTE, 6}, // D2 - PE6 + {&DDRD, &PIND, &PORTD, 6}, // D3 - PD6 + {&DDRD, &PIND, &PORTD, 7}, // D4 - PD7 + {&DDRC, &PINC, &PORTC, 6}, // D5 - PC6 + {&DDRC, &PINC, &PORTC, 7}, // D6 - PC7 + {&DDRE, &PINE, &PORTE, 7}, // D7 - PE7 + {&DDRB, &PINB, &PORTB, 6}, // D8 - PB6 + {&DDRB, &PINB, &PORTB, 5}, // D9 - PB5 + {&DDRB, &PINB, &PORTB, 0}, // D10 - PB0 + {&DDRB, &PINB, &PORTB, 2}, // D11 - MOSI - PB2 + {&DDRB, &PINB, &PORTB, 3}, // D12 -MISO - PB3 + {&DDRB, &PINB, &PORTB, 1}, // D13 -SCK - PB1 + {&DDRF, &PINF, &PORTF, 7}, // D14 - A0 - PF7 + {&DDRF, &PINF, &PORTF, 6}, // D15 - A1 - PF6 + {&DDRF, &PINF, &PORTF, 5}, // D16 - A2 - PF5 + {&DDRF, &PINF, &PORTF, 4}, // D17 - A3 - PF4 + {&DDRD, &PIND, &PORTD, 1}, // D18 - PD1 + {&DDRD, &PIND, &PORTD, 0}, // D19 - PD0 + {&DDRF, &PINF, &PORTF, 1}, // D20 - A6 - PF1 + {&DDRF, &PINF, &PORTF, 0}, // D21 - A7 - PF0 +}; +//------------------------------------------------------------------------------ +#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__) +// Sanguino + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 17; +uint8_t const SCL_PIN = 18; + +// SPI port +uint8_t const SS_PIN = 4; +uint8_t const MOSI_PIN = 5; +uint8_t const MISO_PIN = 6; +uint8_t const SCK_PIN = 7; + +static const pin_map_t digitalPinMap[] = { + {&DDRB, &PINB, &PORTB, 0}, // B0 0 + {&DDRB, &PINB, &PORTB, 1}, // B1 1 + {&DDRB, &PINB, &PORTB, 2}, // B2 2 + {&DDRB, &PINB, &PORTB, 3}, // B3 3 + {&DDRB, &PINB, &PORTB, 4}, // B4 4 + {&DDRB, &PINB, &PORTB, 5}, // B5 5 + {&DDRB, &PINB, &PORTB, 6}, // B6 6 + {&DDRB, &PINB, &PORTB, 7}, // B7 7 + {&DDRD, &PIND, &PORTD, 0}, // D0 8 + {&DDRD, &PIND, &PORTD, 1}, // D1 9 + {&DDRD, &PIND, &PORTD, 2}, // D2 10 + {&DDRD, &PIND, &PORTD, 3}, // D3 11 + {&DDRD, &PIND, &PORTD, 4}, // D4 12 + {&DDRD, &PIND, &PORTD, 5}, // D5 13 + {&DDRD, &PIND, &PORTD, 6}, // D6 14 + {&DDRD, &PIND, &PORTD, 7}, // D7 15 + {&DDRC, &PINC, &PORTC, 0}, // C0 16 + {&DDRC, &PINC, &PORTC, 1}, // C1 17 + {&DDRC, &PINC, &PORTC, 2}, // C2 18 + {&DDRC, &PINC, &PORTC, 3}, // C3 19 + {&DDRC, &PINC, &PORTC, 4}, // C4 20 + {&DDRC, &PINC, &PORTC, 5}, // C5 21 + {&DDRC, &PINC, &PORTC, 6}, // C6 22 + {&DDRC, &PINC, &PORTC, 7}, // C7 23 + {&DDRA, &PINA, &PORTA, 7}, // A7 24 + {&DDRA, &PINA, &PORTA, 6}, // A6 25 + {&DDRA, &PINA, &PORTA, 5}, // A5 26 + {&DDRA, &PINA, &PORTA, 4}, // A4 27 + {&DDRA, &PINA, &PORTA, 3}, // A3 28 + {&DDRA, &PINA, &PORTA, 2}, // A2 29 + {&DDRA, &PINA, &PORTA, 1}, // A1 30 + {&DDRA, &PINA, &PORTA, 0} // A0 31 +}; +//------------------------------------------------------------------------------ +#elif defined(__AVR_ATmega32U4__) +// Leonardo + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 2; +uint8_t const SCL_PIN = 3; + +// SPI port +uint8_t const SS_PIN = 17; +uint8_t const MOSI_PIN = 16; +uint8_t const MISO_PIN = 14; +uint8_t const SCK_PIN = 15; + +static const pin_map_t digitalPinMap[] = { + {&DDRD, &PIND, &PORTD, 2}, // D2 0 + {&DDRD, &PIND, &PORTD, 3}, // D3 1 + {&DDRD, &PIND, &PORTD, 1}, // D1 2 + {&DDRD, &PIND, &PORTD, 0}, // D0 3 + {&DDRD, &PIND, &PORTD, 4}, // D4 4 + {&DDRC, &PINC, &PORTC, 6}, // C6 5 + {&DDRD, &PIND, &PORTD, 7}, // D7 6 + {&DDRE, &PINE, &PORTE, 6}, // E6 7 + {&DDRB, &PINB, &PORTB, 4}, // B4 8 + {&DDRB, &PINB, &PORTB, 5}, // B5 9 + {&DDRB, &PINB, &PORTB, 6}, // B6 10 + {&DDRB, &PINB, &PORTB, 7}, // B7 11 + {&DDRD, &PIND, &PORTD, 6}, // D6 12 + {&DDRC, &PINC, &PORTC, 7}, // C7 13 + {&DDRB, &PINB, &PORTB, 3}, // B3 14 + {&DDRB, &PINB, &PORTB, 1}, // B1 15 + {&DDRB, &PINB, &PORTB, 2}, // B2 16 + {&DDRB, &PINB, &PORTB, 0}, // B0 17 + {&DDRF, &PINF, &PORTF, 7}, // F7 18 + {&DDRF, &PINF, &PORTF, 6}, // F6 19 + {&DDRF, &PINF, &PORTF, 5}, // F5 20 + {&DDRF, &PINF, &PORTF, 4}, // F4 21 + {&DDRF, &PINF, &PORTF, 1}, // F1 22 + {&DDRF, &PINF, &PORTF, 0}, // F0 23 +}; +//------------------------------------------------------------------------------ +#elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__) +// Teensy++ 1.0 & 2.0 + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 1; +uint8_t const SCL_PIN = 0; + +// SPI port +uint8_t const SS_PIN = 20; +uint8_t const MOSI_PIN = 22; +uint8_t const MISO_PIN = 23; +uint8_t const SCK_PIN = 21; + +static const pin_map_t digitalPinMap[] = { + {&DDRD, &PIND, &PORTD, 0}, // D0 0 + {&DDRD, &PIND, &PORTD, 1}, // D1 1 + {&DDRD, &PIND, &PORTD, 2}, // D2 2 + {&DDRD, &PIND, &PORTD, 3}, // D3 3 + {&DDRD, &PIND, &PORTD, 4}, // D4 4 + {&DDRD, &PIND, &PORTD, 5}, // D5 5 + {&DDRD, &PIND, &PORTD, 6}, // D6 6 + {&DDRD, &PIND, &PORTD, 7}, // D7 7 + {&DDRE, &PINE, &PORTE, 0}, // E0 8 + {&DDRE, &PINE, &PORTE, 1}, // E1 9 + {&DDRC, &PINC, &PORTC, 0}, // C0 10 + {&DDRC, &PINC, &PORTC, 1}, // C1 11 + {&DDRC, &PINC, &PORTC, 2}, // C2 12 + {&DDRC, &PINC, &PORTC, 3}, // C3 13 + {&DDRC, &PINC, &PORTC, 4}, // C4 14 + {&DDRC, &PINC, &PORTC, 5}, // C5 15 + {&DDRC, &PINC, &PORTC, 6}, // C6 16 + {&DDRC, &PINC, &PORTC, 7}, // C7 17 + {&DDRE, &PINE, &PORTE, 6}, // E6 18 + {&DDRE, &PINE, &PORTE, 7}, // E7 19 + {&DDRB, &PINB, &PORTB, 0}, // B0 20 + {&DDRB, &PINB, &PORTB, 1}, // B1 21 + {&DDRB, &PINB, &PORTB, 2}, // B2 22 + {&DDRB, &PINB, &PORTB, 3}, // B3 23 + {&DDRB, &PINB, &PORTB, 4}, // B4 24 + {&DDRB, &PINB, &PORTB, 5}, // B5 25 + {&DDRB, &PINB, &PORTB, 6}, // B6 26 + {&DDRB, &PINB, &PORTB, 7}, // B7 27 + {&DDRA, &PINA, &PORTA, 0}, // A0 28 + {&DDRA, &PINA, &PORTA, 1}, // A1 29 + {&DDRA, &PINA, &PORTA, 2}, // A2 30 + {&DDRA, &PINA, &PORTA, 3}, // A3 31 + {&DDRA, &PINA, &PORTA, 4}, // A4 32 + {&DDRA, &PINA, &PORTA, 5}, // A5 33 + {&DDRA, &PINA, &PORTA, 6}, // A6 34 + {&DDRA, &PINA, &PORTA, 7}, // A7 35 + {&DDRE, &PINE, &PORTE, 4}, // E4 36 + {&DDRE, &PINE, &PORTE, 5}, // E5 37 + {&DDRF, &PINF, &PORTF, 0}, // F0 38 + {&DDRF, &PINF, &PORTF, 1}, // F1 39 + {&DDRF, &PINF, &PORTF, 2}, // F2 40 + {&DDRF, &PINF, &PORTF, 3}, // F3 41 + {&DDRF, &PINF, &PORTF, 4}, // F4 42 + {&DDRF, &PINF, &PORTF, 5}, // F5 43 + {&DDRF, &PINF, &PORTF, 6}, // F6 44 + {&DDRF, &PINF, &PORTF, 7} // F7 45 +}; +//------------------------------------------------------------------------------ +#else // defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) +// 168 and 328 Arduinos + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 18; +uint8_t const SCL_PIN = 19; + +// SPI port +uint8_t const SS_PIN = 10; +uint8_t const MOSI_PIN = 11; +uint8_t const MISO_PIN = 12; +uint8_t const SCK_PIN = 13; + +static const pin_map_t digitalPinMap[] = { + {&DDRD, &PIND, &PORTD, 0}, // D0 0 + {&DDRD, &PIND, &PORTD, 1}, // D1 1 + {&DDRD, &PIND, &PORTD, 2}, // D2 2 + {&DDRD, &PIND, &PORTD, 3}, // D3 3 + {&DDRD, &PIND, &PORTD, 4}, // D4 4 + {&DDRD, &PIND, &PORTD, 5}, // D5 5 + {&DDRD, &PIND, &PORTD, 6}, // D6 6 + {&DDRD, &PIND, &PORTD, 7}, // D7 7 + {&DDRB, &PINB, &PORTB, 0}, // B0 8 + {&DDRB, &PINB, &PORTB, 1}, // B1 9 + {&DDRB, &PINB, &PORTB, 2}, // B2 10 + {&DDRB, &PINB, &PORTB, 3}, // B3 11 + {&DDRB, &PINB, &PORTB, 4}, // B4 12 + {&DDRB, &PINB, &PORTB, 5}, // B5 13 + {&DDRC, &PINC, &PORTC, 0}, // C0 14 + {&DDRC, &PINC, &PORTC, 1}, // C1 15 + {&DDRC, &PINC, &PORTC, 2}, // C2 16 + {&DDRC, &PINC, &PORTC, 3}, // C3 17 + {&DDRC, &PINC, &PORTC, 4}, // C4 18 + {&DDRC, &PINC, &PORTC, 5} // C5 19 +}; +#endif // defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) +//------------------------------------------------------------------------------ +static const uint8_t digitalPinCount = sizeof(digitalPinMap)/sizeof(pin_map_t); + +uint8_t badPinNumber(void) + __attribute__((error("Pin number is too large or not a constant"))); + +static inline __attribute__((always_inline)) + uint8_t getPinMode(uint8_t pin) { + if (__builtin_constant_p(pin) && pin < digitalPinCount) { + return (*digitalPinMap[pin].ddr >> digitalPinMap[pin].bit) & 1; + } else { + return badPinNumber(); + } +} +static inline __attribute__((always_inline)) + void setPinMode(uint8_t pin, uint8_t mode) { + if (__builtin_constant_p(pin) && pin < digitalPinCount) { + if (mode) { + *digitalPinMap[pin].ddr |= 1 << digitalPinMap[pin].bit; + } else { + *digitalPinMap[pin].ddr &= ~(1 << digitalPinMap[pin].bit); + } + } else { + badPinNumber(); + } +} +static inline __attribute__((always_inline)) + uint8_t fastDigitalRead(uint8_t pin) { + if (__builtin_constant_p(pin) && pin < digitalPinCount) { + return (*digitalPinMap[pin].pin >> digitalPinMap[pin].bit) & 1; + } else { + return badPinNumber(); + } +} +static inline __attribute__((always_inline)) + void fastDigitalWrite(uint8_t pin, uint8_t value) { + if (__builtin_constant_p(pin) && pin < digitalPinCount) { + if (value) { + *digitalPinMap[pin].port |= 1 << digitalPinMap[pin].bit; + } else { + *digitalPinMap[pin].port &= ~(1 << digitalPinMap[pin].bit); + } + } else { + badPinNumber(); + } +} +#endif // Sd2PinMap_h + +#elif defined (__CPU_ARC__) + +#if defined (__ARDUINO_ARC__) +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 18; +uint8_t const SCL_PIN = 19; + +// SPI port +uint8_t const SS_PIN = 10; +uint8_t const MOSI_PIN = 11; +uint8_t const MISO_PIN = 12; +uint8_t const SCK_PIN = 13; + +#endif // Arduino ARC + +#else +#error Architecture or board not supported. +#endif diff --git a/app/testdata/libraries/SD_1.1.1/SD/src/utility/SdFat.h b/app/testdata/libraries/SD_1.1.1/SD/src/utility/SdFat.h new file mode 100644 index 000000000..3ce3133c4 --- /dev/null +++ b/app/testdata/libraries/SD_1.1.1/SD/src/utility/SdFat.h @@ -0,0 +1,551 @@ +/* Arduino SdFat Library + * Copyright (C) 2009 by William Greiman + * + * This file is part of the Arduino SdFat 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 SdFat Library. If not, see + * . + */ +#ifndef SdFat_h +#define SdFat_h +/** + * \file + * SdFile and SdVolume classes + */ +#if defined (__AVR__) || defined (__CPU_ARC__) +#include +#endif +#include "Sd2Card.h" +#include "FatStructs.h" +#include "Print.h" +//------------------------------------------------------------------------------ +/** + * Allow use of deprecated functions if non-zero + */ +#define ALLOW_DEPRECATED_FUNCTIONS 1 +//------------------------------------------------------------------------------ +// forward declaration since SdVolume is used in SdFile +class SdVolume; +//============================================================================== +// SdFile class + +// 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; +/** ls() flag for recursive list of subdirectories */ +uint8_t const LS_R = 4; + +// use the gnu style oflag in open() +/** open() oflag for reading */ +uint8_t const O_READ = 0X01; +/** open() oflag - same as O_READ */ +uint8_t const O_RDONLY = O_READ; +/** open() oflag for write */ +uint8_t const O_WRITE = 0X02; +/** open() oflag - same as O_WRITE */ +uint8_t const O_WRONLY = O_WRITE; +/** open() oflag for reading and writing */ +uint8_t const O_RDWR = (O_READ | O_WRITE); +/** open() oflag 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; +// values for type_ +/** This SdFile has not been opened. */ +uint8_t const FAT_FILE_TYPE_CLOSED = 0; +/** SdFile for a file */ +uint8_t const FAT_FILE_TYPE_NORMAL = 1; +/** SdFile for a FAT16 root directory */ +uint8_t const FAT_FILE_TYPE_ROOT16 = 2; +/** SdFile for a FAT32 root directory */ +uint8_t const FAT_FILE_TYPE_ROOT32 = 3; +/** SdFile for a subdirectory */ +uint8_t const FAT_FILE_TYPE_SUBDIR = 4; +/** Test value for directory type */ +uint8_t const FAT_FILE_TYPE_MIN_DIR = FAT_FILE_TYPE_ROOT16; + +/** 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); +//------------------------------------------------------------------------------ +/** + * \class SdFile + * \brief Access FAT16 and FAT32 files on SD and SDHC cards. + */ +class SdFile : public Print { + public: + /** Create an instance of SdFile. */ + SdFile(void) : type_(FAT_FILE_TYPE_CLOSED) {} + /** + * writeError is set to true if an error occurs during a write(). + * Set writeError to false before calling print() and/or write() and check + * for true after calls to print() and/or write(). + */ + //bool writeError; + /** + * Cancel unbuffered reads for this file. + * See setUnbufferedRead() + */ + void clearUnbufferedRead(void) { + flags_ &= ~F_FILE_UNBUFFERED_READ; + } + uint8_t close(void); + uint8_t contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock); + uint8_t createContiguous(SdFile* dirFile, + const char* fileName, uint32_t size); + /** \return The current cluster number for a file or directory. */ + uint32_t curCluster(void) const {return curCluster_;} + /** \return The current position for a file or directory. */ + uint32_t curPosition(void) const {return curPosition_;} + /** + * Set the date/time callback function + * + * \param[in] dateTime The user's call back 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) { + // use explicit zero since NULL is not defined for Sanguino + dateTime_ = 0; + } + /** \return Address of the block that contains this file's directory. */ + uint32_t dirBlock(void) const {return dirBlock_;} + uint8_t dirEntry(dir_t* dir); + /** \return Index of this file's directory in the block dirBlock. */ + uint8_t dirIndex(void) const {return dirIndex_;} + static void dirName(const dir_t& dir, char* name); + /** \return The total number of bytes in a file or directory. */ + uint32_t fileSize(void) const {return fileSize_;} + /** \return The first cluster number for a file or directory. */ + uint32_t firstCluster(void) const {return firstCluster_;} + /** \return True if this is a SdFile for a directory else false. */ + uint8_t isDir(void) const {return type_ >= FAT_FILE_TYPE_MIN_DIR;} + /** \return True if this is a SdFile for a file else false. */ + uint8_t isFile(void) const {return type_ == FAT_FILE_TYPE_NORMAL;} + /** \return True if this is a SdFile for an open file/directory else false. */ + uint8_t isOpen(void) const {return type_ != FAT_FILE_TYPE_CLOSED;} + /** \return True if this is a SdFile for a subdirectory else false. */ + uint8_t isSubDir(void) const {return type_ == FAT_FILE_TYPE_SUBDIR;} + /** \return True if this is a SdFile for the root directory. */ + uint8_t isRoot(void) const { + return type_ == FAT_FILE_TYPE_ROOT16 || type_ == FAT_FILE_TYPE_ROOT32; + } + void ls(uint8_t flags = 0, uint8_t indent = 0); + uint8_t makeDir(SdFile* dir, const char* dirName); + uint8_t open(SdFile* dirFile, uint16_t index, uint8_t oflag); + uint8_t open(SdFile* dirFile, const char* fileName, uint8_t oflag); + + uint8_t openRoot(SdVolume* vol); + 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); + /** + * 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 read(void) { + uint8_t b; + return read(&b, 1) == 1 ? b : -1; + } + int16_t read(void* buf, uint16_t nbyte); + int8_t readDir(dir_t* dir); + static uint8_t remove(SdFile* dirFile, const char* fileName); + uint8_t remove(void); + /** Set the file's current position to zero. */ + void rewind(void) { + curPosition_ = curCluster_ = 0; + } + uint8_t rmDir(void); + uint8_t rmRfStar(void); + /** Set the files position to current position + \a pos. See seekSet(). */ + uint8_t seekCur(uint32_t pos) { + return seekSet(curPosition_ + pos); + } + /** + * Set the files current position to end of file. Useful to position + * a file for append. See seekSet(). + */ + uint8_t seekEnd(void) {return seekSet(fileSize_);} + uint8_t seekSet(uint32_t pos); + /** + * Use unbuffered reads to access this file. Used with Wave + * Shield ISR. Used with Sd2Card::partialBlockRead() in WaveRP. + * + * Not recommended for normal applications. + */ + void setUnbufferedRead(void) { + if (isFile()) flags_ |= F_FILE_UNBUFFERED_READ; + } + 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 sync(void); + /** Type of this SdFile. You should use isFile() or isDir() instead of type() + * if possible. + * + * \return The file or directory type. + */ + uint8_t type(void) const {return type_;} + uint8_t truncate(uint32_t size); + /** \return Unbuffered read flag. */ + uint8_t unbufferedRead(void) const { + return flags_ & F_FILE_UNBUFFERED_READ; + } + /** \return SdVolume that contains this file. */ + SdVolume* volume(void) const {return vol_;} + size_t write(uint8_t b); + size_t write(const void* buf, uint16_t nbyte); + size_t write(const char* str); +#ifdef __AVR__ + void write_P(PGM_P str); + void writeln_P(PGM_P str); +#endif +//------------------------------------------------------------------------------ +#if ALLOW_DEPRECATED_FUNCTIONS +// Deprecated functions - suppress cpplint warnings with NOLINT comment + /** \deprecated Use: + * uint8_t SdFile::contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock); + */ + uint8_t contiguousRange(uint32_t& bgnBlock, uint32_t& endBlock) { // NOLINT + return contiguousRange(&bgnBlock, &endBlock); + } + /** \deprecated Use: + * uint8_t SdFile::createContiguous(SdFile* dirFile, + * const char* fileName, uint32_t size) + */ + uint8_t createContiguous(SdFile& dirFile, // NOLINT + const char* fileName, uint32_t size) { + return createContiguous(&dirFile, fileName, size); + } + + /** + * \deprecated Use: + * static void SdFile::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 SdFile::dirEntry(dir_t* dir); */ + uint8_t dirEntry(dir_t& dir) {return dirEntry(&dir);} // NOLINT + /** \deprecated Use: + * uint8_t SdFile::makeDir(SdFile* dir, const char* dirName); + */ + uint8_t makeDir(SdFile& dir, const char* dirName) { // NOLINT + return makeDir(&dir, dirName); + } + /** \deprecated Use: + * uint8_t SdFile::open(SdFile* dirFile, const char* fileName, uint8_t oflag); + */ + uint8_t open(SdFile& dirFile, // NOLINT + const char* fileName, uint8_t oflag) { + return open(&dirFile, fileName, oflag); + } + /** \deprecated Do not use in new apps */ + uint8_t open(SdFile& dirFile, const char* fileName) { // NOLINT + return open(dirFile, fileName, O_RDWR); + } + /** \deprecated Use: + * uint8_t SdFile::open(SdFile* dirFile, uint16_t index, uint8_t oflag); + */ + uint8_t open(SdFile& dirFile, uint16_t index, uint8_t oflag) { // NOLINT + return open(&dirFile, index, oflag); + } + /** \deprecated Use: uint8_t SdFile::openRoot(SdVolume* vol); */ + uint8_t openRoot(SdVolume& vol) {return openRoot(&vol);} // NOLINT + + /** \deprecated Use: int8_t SdFile::readDir(dir_t* dir); */ + int8_t readDir(dir_t& dir) {return readDir(&dir);} // NOLINT + /** \deprecated Use: + * static uint8_t SdFile::remove(SdFile* dirFile, const char* fileName); + */ + static uint8_t remove(SdFile& dirFile, const char* fileName) { // NOLINT + return remove(&dirFile, fileName); + } +//------------------------------------------------------------------------------ +// rest are private + 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: + // bits defined in flags_ + // should be 0XF + static uint8_t const F_OFLAG = (O_ACCMODE | O_APPEND | O_SYNC); + // available bits + static uint8_t const F_UNUSED = 0X30; + // use unbuffered SD read + static uint8_t const F_FILE_UNBUFFERED_READ = 0X40; + // sync of directory entry required + static uint8_t const F_FILE_DIR_DIRTY = 0X80; + +// make sure F_OFLAG is ok +#if ((F_UNUSED | F_FILE_UNBUFFERED_READ | F_FILE_DIR_DIRTY) & F_OFLAG) +#error flags_ bits conflict +#endif // flags_ bits + + // private data + uint8_t flags_; // See above for definition of flags_ bits + uint8_t type_; // type of file see above for values + uint32_t curCluster_; // cluster for current file position + uint32_t curPosition_; // current file position in bytes from beginning + uint32_t dirBlock_; // SD block that contains directory entry for file + uint8_t dirIndex_; // index of entry in dirBlock 0 <= dirIndex_ <= 0XF + uint32_t fileSize_; // file size in bytes + uint32_t firstCluster_; // first cluster of file + SdVolume* vol_; // volume where file is located + + // private functions + uint8_t addCluster(void); + uint8_t addDirCluster(void); + dir_t* cacheDirEntry(uint8_t action); + static void (*dateTime_)(uint16_t* date, uint16_t* time); + static uint8_t make83Name(const char* str, uint8_t* name); + uint8_t openCachedEntry(uint8_t cacheIndex, uint8_t oflags); + dir_t* readDirCache(void); +}; +//============================================================================== +// SdVolume class +/** + * \brief Cache for an SD data block + */ +union cache_t { + /** Used to access cached file data blocks. */ + uint8_t data[512]; + /** Used to access cached FAT16 entries. */ + uint16_t fat16[256]; + /** Used to access cached FAT32 entries. */ + uint32_t fat32[128]; + /** Used to access cached directory entries. */ + dir_t dir[16]; + /** Used to access a cached MasterBoot Record. */ + mbr_t mbr; + /** Used to access to a cached FAT boot sector. */ + fbs_t fbs; +}; +//------------------------------------------------------------------------------ +/** + * \class SdVolume + * \brief Access FAT16 and FAT32 volumes on SD and SDHC cards. + */ +class SdVolume { + public: + /** Create an instance of SdVolume */ + SdVolume(void) :allocSearchStart_(2), fatType_(0) {} + /** Clear the cache and returns a pointer to the cache. Used by the WaveRP + * recorder to do raw write to the SD card. Not for normal apps. + */ + static uint8_t* cacheClear(void) { + cacheFlush(); + cacheBlockNumber_ = 0XFFFFFFFF; + return cacheBuffer_.data; + } + /** + * Initialize a FAT volume. Try partition one first then try super + * floppy format. + * + * \param[in] dev The Sd2Card 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 partition, not finding a valid + * FAT file system or an I/O error. + */ + uint8_t init(Sd2Card* dev) { return init(dev, 1) ? true : init(dev, 0);} + uint8_t init(Sd2Card* dev, uint8_t part); + + // inline functions that return volume info + /** \return The volume's cluster size in blocks. */ + uint8_t blocksPerCluster(void) const {return blocksPerCluster_;} + /** \return The number of blocks in one FAT. */ + uint32_t blocksPerFat(void) const {return blocksPerFat_;} + /** \return The total number of clusters in the volume. */ + uint32_t clusterCount(void) const {return clusterCount_;} + /** \return The shift count required to multiply by blocksPerCluster. */ + uint8_t clusterSizeShift(void) const {return clusterSizeShift_;} + /** \return The logical block number for the start of file data. */ + uint32_t dataStartBlock(void) const {return dataStartBlock_;} + /** \return The number of FAT structures on the volume. */ + uint8_t fatCount(void) const {return fatCount_;} + /** \return The logical block number for the start of the first FAT. */ + uint32_t fatStartBlock(void) const {return fatStartBlock_;} + /** \return The FAT type of the volume. Values are 12, 16 or 32. */ + uint8_t fatType(void) const {return fatType_;} + /** \return The number of entries in the root directory for FAT16 volumes. */ + uint32_t rootDirEntryCount(void) const {return rootDirEntryCount_;} + /** \return The logical block number for the start of the root directory + on FAT16 volumes or the first cluster number on FAT32 volumes. */ + uint32_t rootDirStart(void) const {return rootDirStart_;} + /** return a pointer to the Sd2Card object for this volume */ + static Sd2Card* sdCard(void) {return sdCard_;} +//------------------------------------------------------------------------------ +#if ALLOW_DEPRECATED_FUNCTIONS + // Deprecated functions - suppress cpplint warnings with NOLINT comment + /** \deprecated Use: uint8_t SdVolume::init(Sd2Card* dev); */ + uint8_t init(Sd2Card& dev) {return init(&dev);} // NOLINT + + /** \deprecated Use: uint8_t SdVolume::init(Sd2Card* dev, uint8_t vol); */ + uint8_t init(Sd2Card& dev, uint8_t part) { // NOLINT + return init(&dev, part); + } +#endif // ALLOW_DEPRECATED_FUNCTIONS +//------------------------------------------------------------------------------ + private: + // Allow SdFile access to SdVolume private data. + friend class SdFile; + + // value for action argument in cacheRawBlock to indicate read from cache + static uint8_t const CACHE_FOR_READ = 0; + // value for action argument in cacheRawBlock to indicate cache dirty + static uint8_t const CACHE_FOR_WRITE = 1; + + static cache_t cacheBuffer_; // 512 byte cache for device blocks + static uint32_t cacheBlockNumber_; // Logical number of block in the cache + static Sd2Card* sdCard_; // Sd2Card object for cache + static uint8_t cacheDirty_; // cacheFlush() will write block if true + static uint32_t cacheMirrorBlock_; // block number for mirror FAT +// + uint32_t allocSearchStart_; // start cluster for alloc search + uint8_t blocksPerCluster_; // cluster size in blocks + uint32_t blocksPerFat_; // FAT size in blocks + uint32_t clusterCount_; // clusters in one FAT + uint8_t clusterSizeShift_; // shift to convert cluster count to block count + uint32_t dataStartBlock_; // first data block number + uint8_t fatCount_; // number of FATs on volume + uint32_t fatStartBlock_; // start block for first FAT + uint8_t fatType_; // volume type (12, 16, OR 32) + uint16_t rootDirEntryCount_; // number of entries in FAT16 root dir + uint32_t rootDirStart_; // root start block for FAT16, cluster for FAT32 + //---------------------------------------------------------------------------- + uint8_t allocContiguous(uint32_t count, uint32_t* curCluster); + uint8_t blockOfCluster(uint32_t position) const { + return (position >> 9) & (blocksPerCluster_ - 1);} + uint32_t clusterStartBlock(uint32_t cluster) const { + return dataStartBlock_ + ((cluster - 2) << clusterSizeShift_);} + uint32_t blockNumber(uint32_t cluster, uint32_t position) const { + return clusterStartBlock(cluster) + blockOfCluster(position);} + static uint8_t cacheFlush(void); + static uint8_t cacheRawBlock(uint32_t blockNumber, uint8_t action); + static void cacheSetDirty(void) {cacheDirty_ |= CACHE_FOR_WRITE;} + static uint8_t cacheZeroBlock(uint32_t blockNumber); + uint8_t chainSize(uint32_t beginCluster, uint32_t* size) const; + uint8_t fatGet(uint32_t cluster, uint32_t* value) const; + uint8_t fatPut(uint32_t cluster, uint32_t value); + uint8_t fatPutEOC(uint32_t cluster) { + return fatPut(cluster, 0x0FFFFFFF); + } + uint8_t freeChain(uint32_t cluster); + uint8_t isEOC(uint32_t cluster) const { + return cluster >= (fatType_ == 16 ? FAT16EOC_MIN : FAT32EOC_MIN); + } + uint8_t readBlock(uint32_t block, uint8_t* dst) { + return sdCard_->readBlock(block, dst);} + uint8_t readData(uint32_t block, uint16_t offset, + uint16_t count, uint8_t* dst) { + return sdCard_->readData(block, offset, count, dst); + } + uint8_t writeBlock(uint32_t block, const uint8_t* dst) { + return sdCard_->writeBlock(block, dst); + } +}; +#endif // SdFat_h diff --git a/app/testdata/libraries/SD_1.1.1/SD/src/utility/SdFatUtil.h b/app/testdata/libraries/SD_1.1.1/SD/src/utility/SdFatUtil.h new file mode 100644 index 000000000..d1b4d538f --- /dev/null +++ b/app/testdata/libraries/SD_1.1.1/SD/src/utility/SdFatUtil.h @@ -0,0 +1,75 @@ +/* Arduino SdFat Library + * Copyright (C) 2008 by William Greiman + * + * This file is part of the Arduino SdFat 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 SdFat Library. If not, see + * . + */ +#ifndef SdFatUtil_h +#define SdFatUtil_h +/** + * \file + * Useful utility functions. + */ +#include +#ifdef __AVR__ +#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. */ +#endif +#define NOINLINE __attribute__((noinline,unused)) +#define UNUSEDOK __attribute__((unused)) +//------------------------------------------------------------------------------ +/** Return the number of bytes currently free in RAM. */ +static UNUSEDOK 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; +} +#ifdef __AVR__ +//------------------------------------------------------------------------------ +/** + * %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 // __AVR__ +#endif // #define SdFatUtil_h diff --git a/app/testdata/libraries/SD_1.1.1/SD/src/utility/SdFatmainpage.h b/app/testdata/libraries/SD_1.1.1/SD/src/utility/SdFatmainpage.h new file mode 100644 index 000000000..73b3b63bd --- /dev/null +++ b/app/testdata/libraries/SD_1.1.1/SD/src/utility/SdFatmainpage.h @@ -0,0 +1,202 @@ +/* Arduino SdFat Library + * Copyright (C) 2009 by William Greiman + * + * This file is part of the Arduino SdFat 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 SdFat Library. If not, see + * . + */ + +/** +\mainpage Arduino SdFat Library +
Copyright © 2009 by William Greiman +
+ +\section Intro Introduction +The Arduino SdFat Library is a minimal implementation of FAT16 and FAT32 +file systems on SD flash memory cards. Standard SD and high capacity +SDHC cards are supported. + +The SdFat only supports short 8.3 names. + +The main classes in SdFat are Sd2Card, SdVolume, and SdFile. + +The Sd2Card class supports access to standard SD cards and SDHC cards. Most +applications will only need to call the Sd2Card::init() member function. + +The SdVolume class supports FAT16 and FAT32 partitions. Most applications +will only need to call the SdVolume::init() member function. + +The SdFile class provides file access functions such as open(), read(), +remove(), write(), close() and sync(). This class supports access to the root +directory and subdirectories. + +A number of example are provided in the SdFat/examples folder. These were +developed to test SdFat and illustrate its use. + +SdFat was developed for high speed data recording. SdFat was used to implement +an audio record/play class, WaveRP, for the Adafruit Wave Shield. This +application uses special Sd2Card calls to write to contiguous files in raw mode. +These functions reduce write latency so that audio can be recorded with the +small amount of RAM in the Arduino. + +\section SDcard SD\SDHC 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. + +\section Hardware Hardware Configuration + +SdFat was developed using an + Adafruit Industries + Wave Shield. + +The hardware interface to the SD card should not use a resistor based level +shifter. SdFat 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(SPI_HALF_SPEED) to initialize the SD card. + +\section comment Bugs and Comments + +If you wish to report bugs or have comments, send email to fat16lib@sbcglobal.net. + +\section SdFatClass SdFat Usage + +SdFat 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. + +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. + +\note + The Arduino Print class uses character +at a time writes so it was necessary to use a \link SdFile::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 SdFile::write write() \endlink must call \link SdFile::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 SdFile::close() close() \endlink is called. + +\par +Applications must use care calling \link SdFile::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. + +It is possible to open a file with two or more instances of SdFile. A file may +be corrupted if data is written to the file by more than one instance of SdFile. + +\section HowTo How to format SD Cards as FAT Volumes + +You should use a freshly formatted SD card for best performance. FAT +file systems become slower if many files have been created and deleted. +This is because the directory entry for a deleted file is marked as deleted, +but is not deleted. When a new file is created, these entries must be scanned +before creating the file, a flaw in the FAT design. Also files can become +fragmented which causes reads and writes to be slower. + +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 format is to use SDFormatter +which can be downloaded from: + +http://www.sdcard.org/consumers/formatter/ + +SDFormatter aligns flash erase boundaries with file +system structures which reduces write latency and file system overhead. + +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. + +If you reformat the SD card 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 + +Adafruit Industries: + +http://www.adafruit.com/ + +http://www.ladyada.net/make/waveshield/ + +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 + + + */ diff --git a/app/testdata/libraries/SD_1.1.1/SD/src/utility/SdFile.cpp b/app/testdata/libraries/SD_1.1.1/SD/src/utility/SdFile.cpp new file mode 100644 index 000000000..620fc0d9b --- /dev/null +++ b/app/testdata/libraries/SD_1.1.1/SD/src/utility/SdFile.cpp @@ -0,0 +1,1263 @@ +/* Arduino SdFat Library + * Copyright (C) 2009 by William Greiman + * + * This file is part of the Arduino SdFat 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 SdFat Library. If not, see + * . + */ +#include "SdFat.h" +#ifdef __AVR__ +#include +#endif +#include +//------------------------------------------------------------------------------ +// callback function for date/time +void (*SdFile::dateTime_)(uint16_t* date, uint16_t* time) = NULL; + +#if ALLOW_DEPRECATED_FUNCTIONS +// suppress cpplint warnings with NOLINT comment +void (*SdFile::oldDateTime_)(uint16_t& date, uint16_t& time) = NULL; // NOLINT +#endif // ALLOW_DEPRECATED_FUNCTIONS +//------------------------------------------------------------------------------ +// add a cluster to a file +uint8_t SdFile::addCluster() { + if (!vol_->allocContiguous(1, &curCluster_)) return false; + + // if first cluster of file link to directory entry + if (firstCluster_ == 0) { + firstCluster_ = curCluster_; + flags_ |= F_FILE_DIR_DIRTY; + } + return true; +} +//------------------------------------------------------------------------------ +// Add a cluster to a directory file and zero the cluster. +// return with first block of cluster in the cache +uint8_t SdFile::addDirCluster(void) { + if (!addCluster()) return false; + + // zero data in cluster insure first cluster is in cache + uint32_t block = vol_->clusterStartBlock(curCluster_); + for (uint8_t i = vol_->blocksPerCluster_; i != 0; i--) { + if (!SdVolume::cacheZeroBlock(block + i - 1)) return false; + } + // Increase directory file size by cluster size + fileSize_ += 512UL << vol_->clusterSizeShift_; + return true; +} +//------------------------------------------------------------------------------ +// cache a file's directory entry +// return pointer to cached entry or null for failure +dir_t* SdFile::cacheDirEntry(uint8_t action) { + if (!SdVolume::cacheRawBlock(dirBlock_, action)) return NULL; + return SdVolume::cacheBuffer_.dir + dirIndex_; +} +//------------------------------------------------------------------------------ +/** + * 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 SdFile::close(void) { + if (!sync())return false; + type_ = FAT_FILE_TYPE_CLOSED; + return true; +} +//------------------------------------------------------------------------------ +/** + * Check for contiguous file and return its raw block range. + * + * \param[out] bgnBlock the first block address for the file. + * \param[out] endBlock the last block address 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 not contiguous, file has zero length + * or an I/O error occurred. + */ +uint8_t SdFile::contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock) { + // error if no blocks + if (firstCluster_ == 0) return false; + + for (uint32_t c = firstCluster_; ; c++) { + uint32_t next; + if (!vol_->fatGet(c, &next)) return false; + + // check for contiguous + if (next != (c + 1)) { + // error if not end of chain + if (!vol_->isEOC(next)) return false; + *bgnBlock = vol_->clusterStartBlock(firstCluster_); + *endBlock = vol_->clusterStartBlock(c) + + vol_->blocksPerCluster_ - 1; + return true; + } + } +} +//------------------------------------------------------------------------------ +/** + * Create and open a new contiguous file of a specified size. + * + * \note This function only supports short DOS 8.3 names. + * See open() for more information. + * + * \param[in] dirFile The directory where the file will be created. + * \param[in] fileName A valid DOS 8.3 file name. + * \param[in] size The desired file size. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + * Reasons for failure include \a fileName contains + * an invalid DOS 8.3 file name, the FAT volume has not been initialized, + * a file is already open, the file already exists, the root + * directory is full or an I/O error. + * + */ +uint8_t SdFile::createContiguous(SdFile* dirFile, + const char* fileName, uint32_t size) { + // don't allow zero length file + if (size == 0) return false; + if (!open(dirFile, fileName, O_CREAT | O_EXCL | O_RDWR)) return false; + + // calculate number of clusters needed + uint32_t count = ((size - 1) >> (vol_->clusterSizeShift_ + 9)) + 1; + + // allocate clusters + if (!vol_->allocContiguous(count, &firstCluster_)) { + remove(); + return false; + } + fileSize_ = size; + + // insure sync() will update dir entry + flags_ |= F_FILE_DIR_DIRTY; + return sync(); +} +//------------------------------------------------------------------------------ +/** + * 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 SdFile::dirEntry(dir_t* dir) { + // make sure fields on SD are correct + if (!sync()) return false; + + // read entry + dir_t* p = cacheDirEntry(SdVolume::CACHE_FOR_READ); + if (!p) return false; + + // copy to caller's struct + memcpy(dir, p, sizeof(dir_t)); + return true; +} +//------------------------------------------------------------------------------ +/** + * Format the name field of \a dir into the 13 byte array + * \a name in standard 8.3 short name format. + * + * \param[in] dir The directory structure containing the name. + * \param[out] name A 13 byte char array for the formatted name. + */ +void SdFile::dirName(const dir_t& dir, char* name) { + uint8_t j = 0; + for (uint8_t i = 0; i < 11; i++) { + if (dir.name[i] == ' ')continue; + if (i == 8) name[j++] = '.'; + name[j++] = dir.name[i]; + } + name[j] = 0; +} +//------------------------------------------------------------------------------ +/** List directory contents to Serial. + * + * \param[in] flags The inclusive OR of + * + * LS_DATE - %Print file modification date + * + * LS_SIZE - %Print file size. + * + * LS_R - Recursive list of subdirectories. + * + * \param[in] indent Amount of space before file name. Used for recursive + * list to indicate subdirectory level. + */ +void SdFile::ls(uint8_t flags, uint8_t indent) { + dir_t* p; + + rewind(); + while ((p = readDirCache())) { + // done if past last used entry + if (p->name[0] == DIR_NAME_FREE) break; + + // skip deleted entry and entries for . and .. + if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') continue; + + // only list subdirectories and files + if (!DIR_IS_FILE_OR_SUBDIR(p)) continue; + + // print any indent spaces + for (int8_t i = 0; i < indent; i++) Serial.print(' '); + + // print file name with possible blank fill + printDirName(*p, flags & (LS_DATE | LS_SIZE) ? 14 : 0); + + // print modify date/time if requested + if (flags & LS_DATE) { + printFatDate(p->lastWriteDate); + Serial.print(' '); + printFatTime(p->lastWriteTime); + } + // print size if requested + if (!DIR_IS_SUBDIR(p) && (flags & LS_SIZE)) { + Serial.print(' '); + Serial.print(p->fileSize); + } + Serial.println(); + + // list subdirectory content if requested + if ((flags & LS_R) && DIR_IS_SUBDIR(p)) { + uint16_t index = curPosition()/32 - 1; + SdFile s; + if (s.open(this, index, O_READ)) s.ls(flags, indent + 2); + seekSet(32 * (index + 1)); + } + } +} +//------------------------------------------------------------------------------ +// format directory name field from a 8.3 name string +uint8_t SdFile::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 + uint8_t b; +#if defined(__AVR__) + PGM_P p = PSTR("|<>^+=?/[];,*\"\\"); + while ((b = pgm_read_byte(p++))) if (b == c) return false; +#elif defined(__arm__) + const uint8_t valid[] = "|<>^+=?/[];,*\"\\"; + const uint8_t *p = valid; + while ((b = *p++)) if (b == c) return false; +#endif + // check size 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] != ' '; +} +//------------------------------------------------------------------------------ +/** Make a new directory. + * + * \param[in] dir An open SdFat instance for the directory that will containing + * the new directory. + * + * \param[in] dirName A valid 8.3 DOS name for the new directory. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + * Reasons for failure include this SdFile is already open, \a dir is not a + * directory, \a dirName is invalid or already exists in \a dir. + */ +uint8_t SdFile::makeDir(SdFile* dir, const char* dirName) { + dir_t d; + + // create a normal file + if (!open(dir, dirName, O_CREAT | O_EXCL | O_RDWR)) return false; + + // convert SdFile to directory + flags_ = O_READ; + type_ = FAT_FILE_TYPE_SUBDIR; + + // allocate and zero first cluster + if (!addDirCluster())return false; + + // force entry to SD + if (!sync()) return false; + + // cache entry - should already be in cache due to sync() call + dir_t* p = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); + if (!p) return false; + + // change directory entry attribute + p->attributes = DIR_ATT_DIRECTORY; + + // make entry for '.' + memcpy(&d, p, sizeof(d)); + for (uint8_t i = 1; i < 11; i++) d.name[i] = ' '; + d.name[0] = '.'; + + // cache block for '.' and '..' + uint32_t block = vol_->clusterStartBlock(firstCluster_); + if (!SdVolume::cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) return false; + + // copy '.' to block + memcpy(&SdVolume::cacheBuffer_.dir[0], &d, sizeof(d)); + + // make entry for '..' + d.name[1] = '.'; + if (dir->isRoot()) { + d.firstClusterLow = 0; + d.firstClusterHigh = 0; + } else { + d.firstClusterLow = dir->firstCluster_ & 0XFFFF; + d.firstClusterHigh = dir->firstCluster_ >> 16; + } + // copy '..' to block + memcpy(&SdVolume::cacheBuffer_.dir[1], &d, sizeof(d)); + + // set position after '..' + curPosition_ = 2 * sizeof(d); + + // write first block + return SdVolume::cacheFlush(); +} +//------------------------------------------------------------------------------ +/** + * Open a file or directory by name. + * + * \param[in] dirFile An open SdFat instance for the directory containing the + * file to be opened. + * + * \param[in] fileName A valid 8.3 DOS name for a file to be opened. + * + * \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 at 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. + * + * \note Directory files must be opened read only. Write and truncation is + * not allowed for directory files. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + * Reasons for failure include this SdFile is already open, \a difFile is not + * a directory, \a fileName is invalid, the file does not exist + * or can't be opened in the access mode specified by oflag. + */ +uint8_t SdFile::open(SdFile* dirFile, const char* fileName, uint8_t oflag) { + uint8_t dname[11]; + dir_t* p; + + // error if already open + if (isOpen())return false; + + if (!make83Name(fileName, dname)) return false; + vol_ = dirFile->vol_; + dirFile->rewind(); + + // bool for empty entry found + uint8_t emptyFound = false; + + // search for file + while (dirFile->curPosition_ < dirFile->fileSize_) { + uint8_t index = 0XF & (dirFile->curPosition_ >> 5); + p = dirFile->readDirCache(); + if (p == NULL) return false; + + if (p->name[0] == DIR_NAME_FREE || p->name[0] == DIR_NAME_DELETED) { + // remember first empty slot + if (!emptyFound) { + emptyFound = true; + dirIndex_ = index; + dirBlock_ = SdVolume::cacheBlockNumber_; + } + // 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 found file + return openCachedEntry(0XF & index, oflag); + } + } + // only create file if O_CREAT and O_WRITE + if ((oflag & (O_CREAT | O_WRITE)) != (O_CREAT | O_WRITE)) return false; + + // cache found slot or add cluster if end of file + if (emptyFound) { + p = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); + if (!p) return false; + } else { + if (dirFile->type_ == FAT_FILE_TYPE_ROOT16) return false; + + // add and zero cluster for dirFile - first cluster is in cache for write + if (!dirFile->addDirCluster()) return false; + + // use first entry in cluster + dirIndex_ = 0; + p = SdVolume::cacheBuffer_.dir; + } + // 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; + + // force write of entry to SD + if (!SdVolume::cacheFlush()) return false; + + // open entry in cache + return openCachedEntry(dirIndex_, oflag); +} +//------------------------------------------------------------------------------ +/** + * Open a file by index. + * + * \param[in] dirFile An open SdFat instance for the directory. + * + * \param[in] index The \a index of the directory entry for the file to be + * opened. The value for \a index is (directory file position)/32. + * + * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive + * OR of flags O_READ, O_WRITE, O_TRUNC, and O_SYNC. + * + * See open() by fileName for definition of flags and return values. + * + */ +uint8_t SdFile::open(SdFile* dirFile, uint16_t index, uint8_t oflag) { + // error if already open + if (isOpen())return false; + + // don't open existing file if O_CREAT and O_EXCL - user call error + if ((oflag & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL)) return false; + + vol_ = dirFile->vol_; + + // seek to location of entry + if (!dirFile->seekSet(32 * index)) return false; + + // read entry into cache + dir_t* p = dirFile->readDirCache(); + if (p == NULL) return false; + + // error if empty slot or '.' or '..' + if (p->name[0] == DIR_NAME_FREE || + p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') { + return false; + } + // open cached entry + return openCachedEntry(index & 0XF, oflag); +} +//------------------------------------------------------------------------------ +// open a cached directory entry. Assumes vol_ is initializes +uint8_t SdFile::openCachedEntry(uint8_t dirIndex, uint8_t oflag) { + // location of entry in cache + dir_t* p = SdVolume::cacheBuffer_.dir + dirIndex; + + // write or truncate is an error for a directory or read-only file + if (p->attributes & (DIR_ATT_READ_ONLY | DIR_ATT_DIRECTORY)) { + if (oflag & (O_WRITE | O_TRUNC)) return false; + } + // remember location of directory entry on SD + dirIndex_ = dirIndex; + dirBlock_ = SdVolume::cacheBlockNumber_; + + // copy first cluster number for directory fields + firstCluster_ = (uint32_t)p->firstClusterHigh << 16; + firstCluster_ |= p->firstClusterLow; + + // make sure it is a normal file or subdirectory + if (DIR_IS_FILE(p)) { + fileSize_ = p->fileSize; + type_ = FAT_FILE_TYPE_NORMAL; + } else if (DIR_IS_SUBDIR(p)) { + if (!vol_->chainSize(firstCluster_, &fileSize_)) return false; + type_ = FAT_FILE_TYPE_SUBDIR; + } else { + return false; + } + // save open flags for read/write + flags_ = oflag & (O_ACCMODE | O_SYNC | O_APPEND); + + // set to start of file + curCluster_ = 0; + curPosition_ = 0; + + // truncate file to zero length if requested + if (oflag & O_TRUNC) return truncate(0); + return true; +} +//------------------------------------------------------------------------------ +/** + * Open a volume's root directory. + * + * \param[in] vol The FAT volume containing the root directory to be opened. + * + * \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 + * or it a FAT12 volume. + */ +uint8_t SdFile::openRoot(SdVolume* vol) { + // error if file is already open + if (isOpen()) return false; + + if (vol->fatType() == 16) { + type_ = FAT_FILE_TYPE_ROOT16; + firstCluster_ = 0; + fileSize_ = 32 * vol->rootDirEntryCount(); + } else if (vol->fatType() == 32) { + type_ = FAT_FILE_TYPE_ROOT32; + firstCluster_ = vol->rootDirStart(); + if (!vol->chainSize(firstCluster_, &fileSize_)) return false; + } else { + // volume is not initialized or FAT12 + return false; + } + vol_ = vol; + // read only + flags_ = O_READ; + + // set to start of file + curCluster_ = 0; + curPosition_ = 0; + + // root has no directory entry + dirBlock_ = 0; + dirIndex_ = 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 SdFile::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.print('.'); + w++; + } + Serial.write(dir.name[i]); + w++; + } + if (DIR_IS_SUBDIR(&dir)) { + Serial.print('/'); + w++; + } + while (w < width) { + Serial.print(' '); + w++; + } +} +//------------------------------------------------------------------------------ +/** %Print a directory date field to Serial. + * + * Format is yyyy-mm-dd. + * + * \param[in] fatDate The date field from a directory entry. + */ +void SdFile::printFatDate(uint16_t fatDate) { + Serial.print(FAT_YEAR(fatDate)); + Serial.print('-'); + printTwoDigits(FAT_MONTH(fatDate)); + Serial.print('-'); + 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 SdFile::printFatTime(uint16_t fatTime) { + printTwoDigits(FAT_HOUR(fatTime)); + Serial.print(':'); + printTwoDigits(FAT_MINUTE(fatTime)); + Serial.print(':'); + printTwoDigits(FAT_SECOND(fatTime)); +} +//------------------------------------------------------------------------------ +/** %Print a value as two digits to Serial. + * + * \param[in] v Value to be printed, 0 <= \a v <= 99 + */ +void SdFile::printTwoDigits(uint8_t v) { + char str[3]; + str[0] = '0' + v/10; + str[1] = '0' + v % 10; + str[2] = 0; + Serial.print(str); +} +//------------------------------------------------------------------------------ +/** + * Read data from a file starting at the current 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, will 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, corrupt file system + * or an I/O error occurred. + */ +int16_t SdFile::read(void* buf, uint16_t nbyte) { + uint8_t* dst = reinterpret_cast(buf); + + // error if not open or write only + if (!isOpen() || !(flags_ & O_READ)) return -1; + + // max bytes left in file + if (nbyte > (fileSize_ - curPosition_)) nbyte = fileSize_ - curPosition_; + + // amount left to read + uint16_t toRead = nbyte; + while (toRead > 0) { + uint32_t block; // raw device block number + uint16_t offset = curPosition_ & 0X1FF; // offset in block + if (type_ == FAT_FILE_TYPE_ROOT16) { + block = vol_->rootDirStart() + (curPosition_ >> 9); + } else { + uint8_t blockOfCluster = vol_->blockOfCluster(curPosition_); + if (offset == 0 && blockOfCluster == 0) { + // start of new cluster + if (curPosition_ == 0) { + // use first cluster in file + curCluster_ = firstCluster_; + } else { + // get next cluster from FAT + if (!vol_->fatGet(curCluster_, &curCluster_)) return -1; + } + } + block = vol_->clusterStartBlock(curCluster_) + blockOfCluster; + } + uint16_t n = toRead; + + // amount to be read from current block + if (n > (512 - offset)) n = 512 - offset; + + // no buffering needed if n == 512 or user requests no buffering + if ((unbufferedRead() || n == 512) && + block != SdVolume::cacheBlockNumber_) { + if (!vol_->readData(block, offset, n, dst)) return -1; + dst += n; + } else { + // read block to cache and copy data to caller + if (!SdVolume::cacheRawBlock(block, SdVolume::CACHE_FOR_READ)) return -1; + uint8_t* src = SdVolume::cacheBuffer_.data + offset; + uint8_t* end = src + n; + while (src != end) *dst++ = *src++; + } + curPosition_ += n; + toRead -= n; + } + return nbyte; +} +//------------------------------------------------------------------------------ +/** + * Read the next directory entry from a directory file. + * + * \param[out] dir The dir_t struct that will receive the data. + * + * \return For success readDir() returns the number of bytes read. + * A value of zero will be returned if end of file is reached. + * If an error occurs, readDir() returns -1. Possible errors include + * readDir() called before a directory has been opened, this is not + * a directory file or an I/O error occurred. + */ +int8_t SdFile::readDir(dir_t* dir) { + int8_t n; + // if not a directory file or miss-positioned return an error + if (!isDir() || (0X1F & curPosition_)) return -1; + + while ((n = read(dir, sizeof(dir_t))) == sizeof(dir_t)) { + // last entry if DIR_NAME_FREE + if (dir->name[0] == DIR_NAME_FREE) break; + // skip empty entries and entry for . and .. + if (dir->name[0] == DIR_NAME_DELETED || dir->name[0] == '.') continue; + // return if normal file or subdirectory + if (DIR_IS_FILE_OR_SUBDIR(dir)) return n; + } + // error, end of file, or past last entry + return n < 0 ? -1 : 0; +} +//------------------------------------------------------------------------------ +// Read next directory entry into the cache +// Assumes file is correctly positioned +dir_t* SdFile::readDirCache(void) { + // error if not directory + if (!isDir()) return NULL; + + // index of entry in cache + uint8_t i = (curPosition_ >> 5) & 0XF; + + // use read to locate and cache block + if (read() < 0) return NULL; + + // advance to next entry + curPosition_ += 31; + + // return pointer to entry + return (SdVolume::cacheBuffer_.dir + i); +} +//------------------------------------------------------------------------------ +/** + * 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 read-only, is a directory, + * or an I/O error occurred. + */ +uint8_t SdFile::remove(void) { + // free any clusters - will fail if read-only or directory + if (!truncate(0)) return false; + + // cache directory entry + dir_t* d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); + if (!d) return false; + + // mark entry deleted + d->name[0] = DIR_NAME_DELETED; + + // set this SdFile closed + type_ = FAT_FILE_TYPE_CLOSED; + + // write entry to SD + return SdVolume::cacheFlush(); +} +//------------------------------------------------------------------------------ +/** + * Remove a file. + * + * The directory entry and all data for the file are deleted. + * + * \param[in] dirFile The directory that contains the file. + * \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 a directory, is read only, + * \a dirFile is not a directory, \a fileName is not found + * or an I/O error occurred. + */ +uint8_t SdFile::remove(SdFile* dirFile, const char* fileName) { + SdFile file; + if (!file.open(dirFile, fileName, O_WRITE)) return false; + return file.remove(); +} +//------------------------------------------------------------------------------ +/** Remove a directory file. + * + * The directory file will be removed only if it is empty and is not the + * root directory. rmDir() follows DOS and Windows and ignores the + * read-only attribute for the directory. + * + * \note This function should not be used to delete the 8.3 version of a + * directory that has a long name. For example if a directory has the + * long name "New folder" you should not delete the 8.3 name "NEWFOL~1". + * + * \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 a directory, is the root + * directory, is not empty, or an I/O error occurred. + */ +uint8_t SdFile::rmDir(void) { + // must be open subdirectory + if (!isSubDir()) return false; + + rewind(); + + // make sure directory is empty + while (curPosition_ < fileSize_) { + dir_t* p = readDirCache(); + if (p == NULL) return false; + // done if past last used entry + if (p->name[0] == DIR_NAME_FREE) break; + // skip empty slot or '.' or '..' + if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') continue; + // error not empty + if (DIR_IS_FILE_OR_SUBDIR(p)) return false; + } + // convert empty directory to normal file for remove + type_ = FAT_FILE_TYPE_NORMAL; + flags_ |= O_WRITE; + return remove(); +} +//------------------------------------------------------------------------------ +/** Recursively delete a directory and all contained files. + * + * This is like the Unix/Linux 'rm -rf *' if called with the root directory + * hence the name. + * + * Warning - This will remove all contents of the directory including + * subdirectories. The directory will then be removed if it is not root. + * The read-only attribute for files will be ignored. + * + * \note This function should not be used to delete the 8.3 version of + * a directory that has a long name. See remove() and rmDir(). + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +uint8_t SdFile::rmRfStar(void) { + rewind(); + while (curPosition_ < fileSize_) { + SdFile f; + + // remember position + uint16_t index = curPosition_/32; + + dir_t* p = readDirCache(); + if (!p) return false; + + // done if past last entry + if (p->name[0] == DIR_NAME_FREE) break; + + // skip empty slot or '.' or '..' + if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') continue; + + // skip if part of long file name or volume label in root + if (!DIR_IS_FILE_OR_SUBDIR(p)) continue; + + if (!f.open(this, index, O_READ)) return false; + if (f.isSubDir()) { + // recursively delete + if (!f.rmRfStar()) return false; + } else { + // ignore read-only + f.flags_ |= O_WRITE; + if (!f.remove()) return false; + } + // position to next entry if required + if (curPosition_ != (32u*(index + 1))) { + if (!seekSet(32u*(index + 1))) return false; + } + } + // don't try to delete root + if (isRoot()) return true; + return rmDir(); +} +//------------------------------------------------------------------------------ +/** + * Sets a file's 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 SdFile::seekSet(uint32_t pos) { + // error if file not open or seek past end of file + if (!isOpen() || pos > fileSize_) return false; + + if (type_ == FAT_FILE_TYPE_ROOT16) { + curPosition_ = pos; + return true; + } + if (pos == 0) { + // set position to start of file + curCluster_ = 0; + curPosition_ = 0; + return true; + } + // calculate cluster index for cur and new position + uint32_t nCur = (curPosition_ - 1) >> (vol_->clusterSizeShift_ + 9); + uint32_t nNew = (pos - 1) >> (vol_->clusterSizeShift_ + 9); + + if (nNew < nCur || curPosition_ == 0) { + // must follow chain from first cluster + curCluster_ = firstCluster_; + } else { + // advance from curPosition + nNew -= nCur; + } + while (nNew--) { + if (!vol_->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 SdFile::sync(void) { + // only allow open files and directories + if (!isOpen()) return false; + + if (flags_ & F_FILE_DIR_DIRTY) { + dir_t* d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); + if (!d) return false; + + // do not set filesize for dir files + if (!isDir()) d->fileSize = fileSize_; + + // update first cluster fields + d->firstClusterLow = firstCluster_ & 0XFFFF; + d->firstClusterHigh = firstCluster_ >> 16; + + // set modify time if user supplied a callback date/time function + if (dateTime_) { + dateTime_(&d->lastWriteDate, &d->lastWriteTime); + d->lastAccessDate = d->lastWriteDate; + } + // clear directory dirty + flags_ &= ~F_FILE_DIR_DIRTY; + } + return SdVolume::cacheFlush(); +} +//------------------------------------------------------------------------------ +/** + * Set 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. + * + * \note + * Modify and access timestamps may be overwritten if a date time callback + * function has been set by dateTimeCallback(). + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +uint8_t SdFile::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(SdVolume::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 states + d->creationTimeTenths = second & 1 ? 100 : 0; + } + if (flags & T_WRITE) { + d->lastWriteDate = dirDate; + d->lastWriteTime = dirTime; + } + SdVolume::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 SdFile::truncate(uint32_t length) { +// error if not a normal file or read-only + if (!isFile() || !(flags_ & O_WRITE)) return false; + + // error if length is greater than current size + if (length > fileSize_) return false; + + // fileSize and length are zero - nothing to do + if (fileSize_ == 0) return true; + + // remember position for seek after truncation + uint32_t newPos = curPosition_ > length ? length : curPosition_; + + // position to last cluster in truncated file + if (!seekSet(length)) return false; + + if (length == 0) { + // free all clusters + if (!vol_->freeChain(firstCluster_)) return false; + firstCluster_ = 0; + } else { + uint32_t toFree; + if (!vol_->fatGet(curCluster_, &toFree)) return false; + + if (!vol_->isEOC(toFree)) { + // free extra clusters + if (!vol_->freeChain(toFree)) return false; + + // current cluster is end of chain + if (!vol_->fatPutEOC(curCluster_)) return false; + } + } + fileSize_ = length; + + // need to update directory entry + flags_ |= F_FILE_DIR_DIRTY; + + if (!sync()) return false; + + // set file to correct position + return seekSet(newPos); +} +//------------------------------------------------------------------------------ +/** + * Write data to 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 0. Possible errors + * include write() is called before a file has been opened, write is called + * for a read-only file, device is full, a corrupt file system or an I/O error. + * + */ +size_t SdFile::write(const void* buf, uint16_t nbyte) { + // convert void* to uint8_t* - must be before goto statements + const uint8_t* src = reinterpret_cast(buf); + + // number of bytes left to write - must be before goto statements + uint16_t nToWrite = nbyte; + + // error if not a normal file or is read-only + if (!isFile() || !(flags_ & O_WRITE)) goto writeErrorReturn; + + // seek to end of file if append flag + if ((flags_ & O_APPEND) && curPosition_ != fileSize_) { + if (!seekEnd()) goto writeErrorReturn; + } + + while (nToWrite > 0) { + uint8_t blockOfCluster = vol_->blockOfCluster(curPosition_); + uint16_t blockOffset = curPosition_ & 0X1FF; + if (blockOfCluster == 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 { + uint32_t next; + if (!vol_->fatGet(curCluster_, &next)) return false; + if (vol_->isEOC(next)) { + // add cluster if at end of chain + if (!addCluster()) goto writeErrorReturn; + } else { + curCluster_ = next; + } + } + } + // max space in block + uint16_t n = 512 - blockOffset; + + // lesser of space and amount to write + if (n > nToWrite) n = nToWrite; + + // block for data write + uint32_t block = vol_->clusterStartBlock(curCluster_) + blockOfCluster; + if (n == 512) { + // full block - don't need to use cache + // invalidate cache if block is in cache + if (SdVolume::cacheBlockNumber_ == block) { + SdVolume::cacheBlockNumber_ = 0XFFFFFFFF; + } + if (!vol_->writeBlock(block, src)) goto writeErrorReturn; + src += 512; + } else { + if (blockOffset == 0 && curPosition_ >= fileSize_) { + // start of new block don't need to read into cache + if (!SdVolume::cacheFlush()) goto writeErrorReturn; + SdVolume::cacheBlockNumber_ = block; + SdVolume::cacheSetDirty(); + } else { + // rewrite part of block + if (!SdVolume::cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) { + goto writeErrorReturn; + } + } + uint8_t* dst = SdVolume::cacheBuffer_.data + blockOffset; + uint8_t* end = dst + n; + while (dst != end) *dst++ = *src++; + } + nToWrite -= n; + curPosition_ += 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: + // return for write error + //writeError = true; + setWriteError(); + return 0; +} +//------------------------------------------------------------------------------ +/** + * Write a byte to a file. Required by the Arduino Print class. + * + * Use SdFile::writeError to check for errors. + */ +size_t SdFile::write(uint8_t b) { + return write(&b, 1); +} +//------------------------------------------------------------------------------ +/** + * Write a string to a file. Used by the Arduino Print class. + * + * Use SdFile::writeError to check for errors. + */ +size_t SdFile::write(const char* str) { + return write(str, strlen(str)); +} +#ifdef __AVR__ +//------------------------------------------------------------------------------ +/** + * Write a PROGMEM string to a file. + * + * Use SdFile::writeError to check for errors. + */ +void SdFile::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 SdFile::writeError to check for errors. + */ +void SdFile::writeln_P(PGM_P str) { + write_P(str); + println(); +} +#endif diff --git a/app/testdata/libraries/SD_1.1.1/SD/src/utility/SdInfo.h b/app/testdata/libraries/SD_1.1.1/SD/src/utility/SdInfo.h new file mode 100644 index 000000000..acde74d97 --- /dev/null +++ b/app/testdata/libraries/SD_1.1.1/SD/src/utility/SdInfo.h @@ -0,0 +1,232 @@ +/* Arduino Sd2Card Library + * Copyright (C) 2009 by William Greiman + * + * This file is part of the Arduino Sd2Card 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 Sd2Card 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 +//------------------------------------------------------------------------------ +// SD card commands +/** GO_IDLE_STATE - init card in spi mode if CS low */ +uint8_t const CMD0 = 0X00; +/** SEND_IF_COND - verify SD Memory Card interface operating condition.*/ +uint8_t const CMD8 = 0X08; +/** SEND_CSD - read the Card Specific Data (CSD register) */ +uint8_t const CMD9 = 0X09; +/** SEND_CID - read the card identification information (CID register) */ +uint8_t const CMD10 = 0X0A; +/** SEND_STATUS - read the card status register */ +uint8_t const CMD13 = 0X0D; +/** READ_BLOCK - read a single data block from the card */ +uint8_t const CMD17 = 0X11; +/** WRITE_BLOCK - write a single data block to the card */ +uint8_t const CMD24 = 0X18; +/** WRITE_MULTIPLE_BLOCK - write blocks of data until a STOP_TRANSMISSION */ +uint8_t const CMD25 = 0X19; +/** ERASE_WR_BLK_START - sets the address of the first block to be erased */ +uint8_t const CMD32 = 0X20; +/** ERASE_WR_BLK_END - sets the address of the last block of the continuous + range to be erased*/ +uint8_t const CMD33 = 0X21; +/** ERASE - erase all previously selected blocks */ +uint8_t const CMD38 = 0X26; +/** APP_CMD - escape for application specific command */ +uint8_t const CMD55 = 0X37; +/** READ_OCR - read the OCR register of a card */ +uint8_t const CMD58 = 0X3A; +/** SET_WR_BLK_ERASE_COUNT - Set the number of write blocks to be + pre-erased before writing */ +uint8_t const ACMD23 = 0X17; +/** SD_SEND_OP_COMD - Sends host capacity support information and + activates the card's initialization process */ +uint8_t const ACMD41 = 0X29; +//------------------------------------------------------------------------------ +/** status for card in the ready state */ +uint8_t const R1_READY_STATE = 0X00; +/** status for card in the idle state */ +uint8_t const R1_IDLE_STATE = 0X01; +/** status bit for illegal command */ +uint8_t const R1_ILLEGAL_COMMAND = 0X04; +/** start data token for read or write single block*/ +uint8_t const DATA_START_BLOCK = 0XFE; +/** stop token for write multiple blocks*/ +uint8_t const STOP_TRAN_TOKEN = 0XFD; +/** start data token for write multiple blocks*/ +uint8_t const WRITE_MULTIPLE_TOKEN = 0XFC; +/** mask for data response tokens after a write block operation */ +uint8_t const DATA_RES_MASK = 0X1F; +/** write data accepted token */ +uint8_t const DATA_RES_ACCEPTED = 0X05; +//------------------------------------------------------------------------------ +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; +//------------------------------------------------------------------------------ +// CSD for version 1.00 cards +typedef struct CSDV1 { + // 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; +}csd1_t; +//------------------------------------------------------------------------------ +// CSD for version 2.00 cards +typedef struct CSDV2 { + // 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 reserved2 : 4; + unsigned dsr_imp : 1; + unsigned read_blk_misalign :1; + unsigned write_blk_misalign : 1; + unsigned read_bl_partial : 1; + // byte 7 + unsigned reserved3 : 2; + unsigned c_size_high : 6; + // byte 8 + uint8_t c_size_mid; + // byte 9 + uint8_t c_size_low; + // byte 10 + unsigned sector_size_high : 6; + unsigned erase_blk_en : 1; + unsigned reserved4 : 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 reserved5 : 2; + unsigned wp_grp_enable : 1; + // byte 13 + unsigned reserved6 : 5; + unsigned write_partial : 1; + unsigned write_bl_len_low : 2; + // byte 14 + unsigned reserved7: 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; +}csd2_t; +//------------------------------------------------------------------------------ +// union of old and new style CSD register +union csd_t { + csd1_t v1; + csd2_t v2; +}; +#endif // SdInfo_h diff --git a/app/testdata/libraries/SD_1.1.1/SD/src/utility/SdVolume.cpp b/app/testdata/libraries/SD_1.1.1/SD/src/utility/SdVolume.cpp new file mode 100644 index 000000000..2fbb8100b --- /dev/null +++ b/app/testdata/libraries/SD_1.1.1/SD/src/utility/SdVolume.cpp @@ -0,0 +1,295 @@ +/* Arduino SdFat Library + * Copyright (C) 2009 by William Greiman + * + * This file is part of the Arduino SdFat 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 SdFat Library. If not, see + * . + */ +#include "SdFat.h" +//------------------------------------------------------------------------------ +// raw block cache +// init cacheBlockNumber_to invalid SD block number +uint32_t SdVolume::cacheBlockNumber_ = 0XFFFFFFFF; +cache_t SdVolume::cacheBuffer_; // 512 byte cache for Sd2Card +Sd2Card* SdVolume::sdCard_; // pointer to SD card object +uint8_t SdVolume::cacheDirty_ = 0; // cacheFlush() will write block if true +uint32_t SdVolume::cacheMirrorBlock_ = 0; // mirror block for second FAT +//------------------------------------------------------------------------------ +// find a contiguous group of clusters +uint8_t SdVolume::allocContiguous(uint32_t count, uint32_t* curCluster) { + // start of group + uint32_t bgnCluster; + + // flag to save place to start next search + uint8_t setStart; + + // set search start cluster + if (*curCluster) { + // try to make file contiguous + bgnCluster = *curCluster + 1; + + // don't save new start location + setStart = false; + } else { + // start at likely place for free cluster + bgnCluster = allocSearchStart_; + + // save next search start if one cluster + setStart = 1 == count; + } + // end of group + uint32_t endCluster = bgnCluster; + + // last cluster of FAT + uint32_t fatEnd = clusterCount_ + 1; + + // search the FAT for free clusters + for (uint32_t n = 0;; n++, endCluster++) { + // can't find space checked all clusters + if (n >= clusterCount_) return false; + + // past end - start from beginning of FAT + if (endCluster > fatEnd) { + bgnCluster = endCluster = 2; + } + uint32_t f; + if (!fatGet(endCluster, &f)) return false; + + if (f != 0) { + // cluster in use try next cluster as bgnCluster + bgnCluster = endCluster + 1; + } else if ((endCluster - bgnCluster + 1) == count) { + // done - found space + break; + } + } + // mark end of chain + if (!fatPutEOC(endCluster)) return false; + + // link clusters + while (endCluster > bgnCluster) { + if (!fatPut(endCluster - 1, endCluster)) return false; + endCluster--; + } + if (*curCluster != 0) { + // connect chains + if (!fatPut(*curCluster, bgnCluster)) return false; + } + // return first cluster number to caller + *curCluster = bgnCluster; + + // remember possible next free cluster + if (setStart) allocSearchStart_ = bgnCluster + 1; + + return true; +} +//------------------------------------------------------------------------------ +uint8_t SdVolume::cacheFlush(void) { + if (cacheDirty_) { + if (!sdCard_->writeBlock(cacheBlockNumber_, cacheBuffer_.data)) { + return false; + } + // mirror FAT tables + if (cacheMirrorBlock_) { + if (!sdCard_->writeBlock(cacheMirrorBlock_, cacheBuffer_.data)) { + return false; + } + cacheMirrorBlock_ = 0; + } + cacheDirty_ = 0; + } + return true; +} +//------------------------------------------------------------------------------ +uint8_t SdVolume::cacheRawBlock(uint32_t blockNumber, uint8_t action) { + if (cacheBlockNumber_ != blockNumber) { + if (!cacheFlush()) return false; + if (!sdCard_->readBlock(blockNumber, cacheBuffer_.data)) return false; + cacheBlockNumber_ = blockNumber; + } + cacheDirty_ |= action; + return true; +} +//------------------------------------------------------------------------------ +// cache a zero block for blockNumber +uint8_t SdVolume::cacheZeroBlock(uint32_t blockNumber) { + if (!cacheFlush()) return false; + + // loop take less flash than memset(cacheBuffer_.data, 0, 512); + for (uint16_t i = 0; i < 512; i++) { + cacheBuffer_.data[i] = 0; + } + cacheBlockNumber_ = blockNumber; + cacheSetDirty(); + return true; +} +//------------------------------------------------------------------------------ +// return the size in bytes of a cluster chain +uint8_t SdVolume::chainSize(uint32_t cluster, uint32_t* size) const { + uint32_t s = 0; + do { + if (!fatGet(cluster, &cluster)) return false; + s += 512UL << clusterSizeShift_; + } while (!isEOC(cluster)); + *size = s; + return true; +} +//------------------------------------------------------------------------------ +// Fetch a FAT entry +uint8_t SdVolume::fatGet(uint32_t cluster, uint32_t* value) const { + if (cluster > (clusterCount_ + 1)) return false; + uint32_t lba = fatStartBlock_; + lba += fatType_ == 16 ? cluster >> 8 : cluster >> 7; + if (lba != cacheBlockNumber_) { + if (!cacheRawBlock(lba, CACHE_FOR_READ)) return false; + } + if (fatType_ == 16) { + *value = cacheBuffer_.fat16[cluster & 0XFF]; + } else { + *value = cacheBuffer_.fat32[cluster & 0X7F] & FAT32MASK; + } + return true; +} +//------------------------------------------------------------------------------ +// Store a FAT entry +uint8_t SdVolume::fatPut(uint32_t cluster, uint32_t value) { + // error if reserved cluster + if (cluster < 2) return false; + + // error if not in FAT + if (cluster > (clusterCount_ + 1)) return false; + + // calculate block address for entry + uint32_t lba = fatStartBlock_; + lba += fatType_ == 16 ? cluster >> 8 : cluster >> 7; + + if (lba != cacheBlockNumber_) { + if (!cacheRawBlock(lba, CACHE_FOR_READ)) return false; + } + // store entry + if (fatType_ == 16) { + cacheBuffer_.fat16[cluster & 0XFF] = value; + } else { + cacheBuffer_.fat32[cluster & 0X7F] = value; + } + cacheSetDirty(); + + // mirror second FAT + if (fatCount_ > 1) cacheMirrorBlock_ = lba + blocksPerFat_; + return true; +} +//------------------------------------------------------------------------------ +// free a cluster chain +uint8_t SdVolume::freeChain(uint32_t cluster) { + // clear free cluster location + allocSearchStart_ = 2; + + do { + uint32_t next; + if (!fatGet(cluster, &next)) return false; + + // free cluster + if (!fatPut(cluster, 0)) return false; + + cluster = next; + } while (!isEOC(cluster)); + + return true; +} +//------------------------------------------------------------------------------ +/** + * Initialize a FAT volume. + * + * \param[in] dev The SD card 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 partition, not finding a valid + * FAT file system in the specified partition or an I/O error. + */ +uint8_t SdVolume::init(Sd2Card* dev, uint8_t part) { + uint32_t volumeStartBlock = 0; + sdCard_ = dev; + // if part == 0 assume super floppy with FAT boot sector in block zero + // if part > 0 assume mbr volume with partition table + if (part) { + if (part > 4)return false; + if (!cacheRawBlock(volumeStartBlock, CACHE_FOR_READ)) return false; + part_t* p = &cacheBuffer_.mbr.part[part-1]; + if ((p->boot & 0X7F) !=0 || + p->totalSectors < 100 || + p->firstSector == 0) { + // not a valid partition + return false; + } + volumeStartBlock = p->firstSector; + } + if (!cacheRawBlock(volumeStartBlock, CACHE_FOR_READ)) return false; + bpb_t* bpb = &cacheBuffer_.fbs.bpb; + if (bpb->bytesPerSector != 512 || + bpb->fatCount == 0 || + bpb->reservedSectorCount == 0 || + bpb->sectorsPerCluster == 0) { + // not valid FAT volume + return false; + } + fatCount_ = bpb->fatCount; + blocksPerCluster_ = bpb->sectorsPerCluster; + + // determine shift that is same as multiply by blocksPerCluster_ + clusterSizeShift_ = 0; + while (blocksPerCluster_ != (1 << clusterSizeShift_)) { + // error if not power of 2 + if (clusterSizeShift_++ > 7) return false; + } + blocksPerFat_ = bpb->sectorsPerFat16 ? + bpb->sectorsPerFat16 : bpb->sectorsPerFat32; + + fatStartBlock_ = volumeStartBlock + bpb->reservedSectorCount; + + // count for FAT16 zero for FAT32 + rootDirEntryCount_ = bpb->rootDirEntryCount; + + // directory start for FAT16 dataStart for FAT32 + rootDirStart_ = fatStartBlock_ + bpb->fatCount * blocksPerFat_; + + // data start for FAT16 and FAT32 + dataStartBlock_ = rootDirStart_ + ((32 * bpb->rootDirEntryCount + 511)/512); + + // total blocks for FAT16 or FAT32 + uint32_t totalBlocks = bpb->totalSectors16 ? + bpb->totalSectors16 : bpb->totalSectors32; + // total data blocks + clusterCount_ = totalBlocks - (dataStartBlock_ - volumeStartBlock); + + // divide by cluster size to get cluster count + clusterCount_ >>= clusterSizeShift_; + + // FAT type is determined by cluster count + if (clusterCount_ < 4085) { + fatType_ = 12; + } else if (clusterCount_ < 65525) { + fatType_ = 16; + } else { + rootDirStart_ = bpb->fat32RootCluster; + fatType_ = 32; + } + return true; +} diff --git a/app/testdata/libraries/SD_1.2.1/SD/README.adoc b/app/testdata/libraries/SD_1.2.1/SD/README.adoc new file mode 100644 index 000000000..fabff563c --- /dev/null +++ b/app/testdata/libraries/SD_1.2.1/SD/README.adoc @@ -0,0 +1,24 @@ += SD Library for Arduino = + +The SD library allows for reading from and writing to SD cards. + +For more information about this library please visit us at +http://www.arduino.cc/en/Reference/SD + +== License == + + Copyright (C) 2009 by William Greiman +Copyright (c) 2010 SparkFun Electronics + +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 3 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, see . diff --git a/app/testdata/libraries/SD_1.2.1/SD/examples/CardInfo/CardInfo.ino b/app/testdata/libraries/SD_1.2.1/SD/examples/CardInfo/CardInfo.ino new file mode 100644 index 000000000..97913efde --- /dev/null +++ b/app/testdata/libraries/SD_1.2.1/SD/examples/CardInfo/CardInfo.ino @@ -0,0 +1,116 @@ +/* + SD card test + + This example shows how use the utility libraries on which the' + SD library is based in order to get info about your SD card. + Very useful for testing a card when you're not sure whether its working or not. + + The circuit: + SD card attached to SPI bus as follows: + ** MOSI - pin 11 on Arduino Uno/Duemilanove/Diecimila + ** MISO - pin 12 on Arduino Uno/Duemilanove/Diecimila + ** CLK - pin 13 on Arduino Uno/Duemilanove/Diecimila + ** CS - depends on your SD card shield or module. + Pin 4 used here for consistency with other Arduino examples + + + created 28 Mar 2011 + by Limor Fried + modified 9 Apr 2012 + by Tom Igoe +*/ +// include the SD library: +#include +#include + +// set up variables using the SD utility library functions: +Sd2Card card; +SdVolume volume; +SdFile root; + +// change this to match your SD shield or module; +// Arduino Ethernet shield: pin 4 +// Adafruit SD shields and modules: pin 10 +// Sparkfun SD shield: pin 8 +// MKRZero SD: SDCARD_SS_PIN +const int chipSelect = 4; + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + + Serial.print("\nInitializing SD card..."); + + // we'll use the initialization code from the utility libraries + // since we're just testing if the card is working! + if (!card.init(SPI_HALF_SPEED, chipSelect)) { + Serial.println("initialization failed. Things to check:"); + Serial.println("* is a card inserted?"); + Serial.println("* is your wiring correct?"); + Serial.println("* did you change the chipSelect pin to match your shield or module?"); + while (1); + } else { + Serial.println("Wiring is correct and a card is present."); + } + + // print the type of card + Serial.println(); + Serial.print("Card type: "); + switch (card.type()) { + case SD_CARD_TYPE_SD1: + Serial.println("SD1"); + break; + case SD_CARD_TYPE_SD2: + Serial.println("SD2"); + break; + case SD_CARD_TYPE_SDHC: + Serial.println("SDHC"); + break; + default: + Serial.println("Unknown"); + } + + // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32 + if (!volume.init(card)) { + Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card"); + while (1); + } + + Serial.print("Clusters: "); + Serial.println(volume.clusterCount()); + Serial.print("Blocks x Cluster: "); + Serial.println(volume.blocksPerCluster()); + + Serial.print("Total Blocks: "); + Serial.println(volume.blocksPerCluster() * volume.clusterCount()); + Serial.println(); + + // print the type and size of the first FAT-type volume + uint32_t volumesize; + Serial.print("Volume type is: FAT"); + Serial.println(volume.fatType(), DEC); + + volumesize = volume.blocksPerCluster(); // clusters are collections of blocks + volumesize *= volume.clusterCount(); // we'll have a lot of clusters + volumesize /= 2; // SD card blocks are always 512 bytes (2 blocks are 1KB) + Serial.print("Volume size (Kb): "); + Serial.println(volumesize); + Serial.print("Volume size (Mb): "); + volumesize /= 1024; + Serial.println(volumesize); + Serial.print("Volume size (Gb): "); + Serial.println((float)volumesize / 1024.0); + + Serial.println("\nFiles found on the card (name, date and size in bytes): "); + root.openRoot(volume); + + // list all files in the card with date and size + root.ls(LS_R | LS_DATE | LS_SIZE); +} + +void loop(void) { +} diff --git a/app/testdata/libraries/SD_1.2.1/SD/examples/Datalogger/Datalogger.ino b/app/testdata/libraries/SD_1.2.1/SD/examples/Datalogger/Datalogger.ino new file mode 100644 index 000000000..a3e3c1106 --- /dev/null +++ b/app/testdata/libraries/SD_1.2.1/SD/examples/Datalogger/Datalogger.ino @@ -0,0 +1,84 @@ +/* + SD card datalogger + + This example shows how to log data from three analog sensors + to an SD card using the SD library. + + The circuit: + * analog sensors on analog ins 0, 1, and 2 + * SD card attached to SPI bus as follows: + ** MOSI - pin 11 + ** MISO - pin 12 + ** CLK - pin 13 + ** CS - pin 4 (for MKRZero SD: SDCARD_SS_PIN) + + created 24 Nov 2010 + modified 9 Apr 2012 + by Tom Igoe + + This example code is in the public domain. + + */ + +#include +#include + +const int chipSelect = 4; + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + + Serial.print("Initializing SD card..."); + + // see if the card is present and can be initialized: + if (!SD.begin(chipSelect)) { + Serial.println("Card failed, or not present"); + // don't do anything more: + while (1); + } + Serial.println("card initialized."); +} + +void loop() { + // make a string for assembling the data to log: + String dataString = ""; + + // read three sensors and append to the string: + for (int analogPin = 0; analogPin < 3; analogPin++) { + int sensor = analogRead(analogPin); + dataString += String(sensor); + if (analogPin < 2) { + dataString += ","; + } + } + + // open the file. note that only one file can be open at a time, + // so you have to close this one before opening another. + File dataFile = SD.open("datalog.txt", FILE_WRITE); + + // if the file is available, write to it: + if (dataFile) { + dataFile.println(dataString); + dataFile.close(); + // print to the serial port too: + Serial.println(dataString); + } + // if the file isn't open, pop up an error: + else { + Serial.println("error opening datalog.txt"); + } +} + + + + + + + + + diff --git a/app/testdata/libraries/SD_1.2.1/SD/examples/DumpFile/DumpFile.ino b/app/testdata/libraries/SD_1.2.1/SD/examples/DumpFile/DumpFile.ino new file mode 100644 index 000000000..421f2d9e8 --- /dev/null +++ b/app/testdata/libraries/SD_1.2.1/SD/examples/DumpFile/DumpFile.ino @@ -0,0 +1,65 @@ +/* + SD card file dump + + This example shows how to read a file from the SD card using the + SD library and send it over the serial port. + + The circuit: + * SD card attached to SPI bus as follows: + ** MOSI - pin 11 + ** MISO - pin 12 + ** CLK - pin 13 + ** CS - pin 4 (for MKRZero SD: SDCARD_SS_PIN) + + created 22 December 2010 + by Limor Fried + modified 9 Apr 2012 + by Tom Igoe + + This example code is in the public domain. + + */ + +#include +#include + +const int chipSelect = 4; + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + + Serial.print("Initializing SD card..."); + + // see if the card is present and can be initialized: + if (!SD.begin(chipSelect)) { + Serial.println("Card failed, or not present"); + // don't do anything more: + while (1); + } + Serial.println("card initialized."); + + // open the file. note that only one file can be open at a time, + // so you have to close this one before opening another. + File dataFile = SD.open("datalog.txt"); + + // if the file is available, write to it: + if (dataFile) { + while (dataFile.available()) { + Serial.write(dataFile.read()); + } + dataFile.close(); + } + // if the file isn't open, pop up an error: + else { + Serial.println("error opening datalog.txt"); + } +} + +void loop() { +} + diff --git a/app/testdata/libraries/SD_1.2.1/SD/examples/Files/Files.ino b/app/testdata/libraries/SD_1.2.1/SD/examples/Files/Files.ino new file mode 100644 index 000000000..9b1b19d93 --- /dev/null +++ b/app/testdata/libraries/SD_1.2.1/SD/examples/Files/Files.ino @@ -0,0 +1,75 @@ +/* + SD card basic file example + + This example shows how to create and destroy an SD card file + The circuit: + * SD card attached to SPI bus as follows: + ** MOSI - pin 11 + ** MISO - pin 12 + ** CLK - pin 13 + ** CS - pin 4 (for MKRZero SD: SDCARD_SS_PIN) + + created Nov 2010 + by David A. Mellis + modified 9 Apr 2012 + by Tom Igoe + + This example code is in the public domain. + + */ +#include +#include + +File myFile; + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + + Serial.print("Initializing SD card..."); + + if (!SD.begin(4)) { + Serial.println("initialization failed!"); + while (1); + } + Serial.println("initialization done."); + + if (SD.exists("example.txt")) { + Serial.println("example.txt exists."); + } else { + Serial.println("example.txt doesn't exist."); + } + + // open a new file and immediately close it: + Serial.println("Creating example.txt..."); + myFile = SD.open("example.txt", FILE_WRITE); + myFile.close(); + + // Check to see if the file exists: + if (SD.exists("example.txt")) { + Serial.println("example.txt exists."); + } else { + Serial.println("example.txt doesn't exist."); + } + + // delete the file: + Serial.println("Removing example.txt..."); + SD.remove("example.txt"); + + if (SD.exists("example.txt")) { + Serial.println("example.txt exists."); + } else { + Serial.println("example.txt doesn't exist."); + } +} + +void loop() { + // nothing happens after setup finishes. +} + + + diff --git a/app/testdata/libraries/SD_1.2.1/SD/examples/ReadWrite/ReadWrite.ino b/app/testdata/libraries/SD_1.2.1/SD/examples/ReadWrite/ReadWrite.ino new file mode 100644 index 000000000..8e4bd829c --- /dev/null +++ b/app/testdata/libraries/SD_1.2.1/SD/examples/ReadWrite/ReadWrite.ino @@ -0,0 +1,79 @@ +/* + SD card read/write + + This example shows how to read and write data to and from an SD card file + The circuit: + * SD card attached to SPI bus as follows: + ** MOSI - pin 11 + ** MISO - pin 12 + ** CLK - pin 13 + ** CS - pin 4 (for MKRZero SD: SDCARD_SS_PIN) + + created Nov 2010 + by David A. Mellis + modified 9 Apr 2012 + by Tom Igoe + + This example code is in the public domain. + + */ + +#include +#include + +File myFile; + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + + Serial.print("Initializing SD card..."); + + if (!SD.begin(4)) { + Serial.println("initialization failed!"); + while (1); + } + Serial.println("initialization done."); + + // open the file. note that only one file can be open at a time, + // so you have to close this one before opening another. + myFile = SD.open("test.txt", FILE_WRITE); + + // if the file opened okay, write to it: + if (myFile) { + Serial.print("Writing to test.txt..."); + myFile.println("testing 1, 2, 3."); + // close the file: + myFile.close(); + Serial.println("done."); + } else { + // if the file didn't open, print an error: + Serial.println("error opening test.txt"); + } + + // re-open the file for reading: + myFile = SD.open("test.txt"); + if (myFile) { + Serial.println("test.txt:"); + + // read from the file until there's nothing else in it: + while (myFile.available()) { + Serial.write(myFile.read()); + } + // close the file: + myFile.close(); + } else { + // if the file didn't open, print an error: + Serial.println("error opening test.txt"); + } +} + +void loop() { + // nothing happens after setup +} + + diff --git a/app/testdata/libraries/SD_1.2.1/SD/examples/listfiles/listfiles.ino b/app/testdata/libraries/SD_1.2.1/SD/examples/listfiles/listfiles.ino new file mode 100644 index 000000000..7c4ee5c8e --- /dev/null +++ b/app/testdata/libraries/SD_1.2.1/SD/examples/listfiles/listfiles.ino @@ -0,0 +1,80 @@ +/* + Listfiles + + 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 + ** MISO - pin 12 + ** CLK - pin 13 + ** CS - pin 4 (for MKRZero SD: SDCARD_SS_PIN) + + created Nov 2010 + 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. + + */ +#include +#include + +File root; + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + Serial.print("Initializing SD card..."); + + if (!SD.begin(4)) { + Serial.println("initialization failed!"); + while (1); + } + Serial.println("initialization done."); + + root = SD.open("/"); + + printDirectory(root, 0); + + Serial.println("done!"); +} + +void loop() { + // nothing happens after setup finishes. +} + +void printDirectory(File dir, int numTabs) { + while (true) { + + File entry = dir.openNextFile(); + if (! entry) { + // no more files + break; + } + for (uint8_t i = 0; i < numTabs; i++) { + Serial.print('\t'); + } + Serial.print(entry.name()); + if (entry.isDirectory()) { + Serial.println("/"); + printDirectory(entry, numTabs + 1); + } else { + // files have sizes, directories do not + Serial.print("\t\t"); + Serial.println(entry.size(), DEC); + } + entry.close(); + } +} + + + diff --git a/app/testdata/libraries/SD_1.2.1/SD/keywords.txt b/app/testdata/libraries/SD_1.2.1/SD/keywords.txt new file mode 100644 index 000000000..91e74b830 --- /dev/null +++ b/app/testdata/libraries/SD_1.2.1/SD/keywords.txt @@ -0,0 +1,31 @@ +####################################### +# Syntax Coloring Map SD +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +SD KEYWORD1 SD +File KEYWORD1 SD +SDFile KEYWORD1 SD + +####################################### +# Methods and Functions (KEYWORD2) +####################################### +begin KEYWORD2 +exists KEYWORD2 +mkdir KEYWORD2 +remove KEYWORD2 +rmdir KEYWORD2 +open KEYWORD2 +close KEYWORD2 +seek KEYWORD2 +position KEYWORD2 +size KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### +FILE_READ LITERAL1 +FILE_WRITE LITERAL1 diff --git a/app/testdata/libraries/SD_1.2.1/SD/library.properties b/app/testdata/libraries/SD_1.2.1/SD/library.properties new file mode 100644 index 000000000..0e4c54343 --- /dev/null +++ b/app/testdata/libraries/SD_1.2.1/SD/library.properties @@ -0,0 +1,9 @@ +name=SD +version=1.2.1 +author=Arduino, SparkFun +maintainer=Arduino +sentence=Enables reading and writing on SD cards. +paragraph=Once an SD memory card is connected to the SPI interface of the Arduino or Genuino board you can create files and read/write on them. You can also move through directories on the SD card. +category=Data Storage +url=http://www.arduino.cc/en/Reference/SD +architectures=avr,sam,samd,arc32 diff --git a/app/testdata/libraries/SD_1.2.1/SD/src/File.cpp b/app/testdata/libraries/SD_1.2.1/SD/src/File.cpp new file mode 100644 index 000000000..6eee39aa1 --- /dev/null +++ b/app/testdata/libraries/SD_1.2.1/SD/src/File.cpp @@ -0,0 +1,146 @@ +/* + + SD - a slightly more friendly wrapper for sdfatlib + + This library aims to expose a subset of SD card functionality + in the form of a higher level "wrapper" object. + + License: GNU General Public License V3 + (Because sdfatlib is licensed with this.) + + (C) Copyright 2010 SparkFun Electronics + + */ + +#include + +/* for debugging file open/close leaks + uint8_t nfilecount=0; +*/ + +File::File(SdFile f, const char *n) { + // oh man you are kidding me, new() doesnt exist? Ok we do it by hand! + _file = (SdFile *)malloc(sizeof(SdFile)); + if (_file) { + memcpy(_file, &f, sizeof(SdFile)); + + strncpy(_name, n, 12); + _name[12] = 0; + + /* for debugging file open/close leaks + nfilecount++; + Serial.print("Created \""); + Serial.print(n); + Serial.print("\": "); + Serial.println(nfilecount, DEC); + */ + } +} + +File::File(void) { + _file = 0; + _name[0] = 0; + //Serial.print("Created empty file object"); +} + +// returns a pointer to the file name +char *File::name(void) { + return _name; +} + +// a directory is a special type of file +boolean File::isDirectory(void) { + return (_file && _file->isDir()); +} + + +size_t File::write(uint8_t val) { + return write(&val, 1); +} + +size_t File::write(const uint8_t *buf, size_t size) { + size_t t; + if (!_file) { + setWriteError(); + return 0; + } + _file->clearWriteError(); + t = _file->write(buf, size); + if (_file->getWriteError()) { + setWriteError(); + return 0; + } + return t; +} + +int File::peek() { + if (! _file) + return 0; + + int c = _file->read(); + if (c != -1) _file->seekCur(-1); + return c; +} + +int File::read() { + if (_file) + return _file->read(); + return -1; +} + +// buffered read for more efficient, high speed reading +int File::read(void *buf, uint16_t nbyte) { + if (_file) + return _file->read(buf, nbyte); + return 0; +} + +int File::available() { + if (! _file) return 0; + + uint32_t n = size() - position(); + + return n > 0X7FFF ? 0X7FFF : n; +} + +void File::flush() { + if (_file) + _file->sync(); +} + +boolean File::seek(uint32_t pos) { + if (! _file) return false; + + return _file->seekSet(pos); +} + +uint32_t File::position() { + if (! _file) return -1; + return _file->curPosition(); +} + +uint32_t File::size() { + if (! _file) return 0; + return _file->fileSize(); +} + +void File::close() { + if (_file) { + _file->close(); + free(_file); + _file = 0; + + /* for debugging file open/close leaks + nfilecount--; + Serial.print("Deleted "); + Serial.println(nfilecount, DEC); + */ + } +} + +File::operator bool() { + if (_file) + return _file->isOpen(); + return false; +} + diff --git a/app/testdata/libraries/SD_1.2.1/SD/src/README.txt b/app/testdata/libraries/SD_1.2.1/SD/src/README.txt new file mode 100644 index 000000000..495ea4c79 --- /dev/null +++ b/app/testdata/libraries/SD_1.2.1/SD/src/README.txt @@ -0,0 +1,13 @@ + +** SD - a slightly more friendly wrapper for sdfatlib ** + +This library aims to expose a subset of SD card functionality in the +form of a higher level "wrapper" object. + +License: GNU General Public License V3 + (Because sdfatlib is licensed with this.) + +(C) Copyright 2010 SparkFun Electronics + +Now better than ever with optimization, multiple file support, directory handling, etc - ladyada! + diff --git a/app/testdata/libraries/SD_1.2.1/SD/src/SD.cpp b/app/testdata/libraries/SD_1.2.1/SD/src/SD.cpp new file mode 100644 index 000000000..fbadb628b --- /dev/null +++ b/app/testdata/libraries/SD_1.2.1/SD/src/SD.cpp @@ -0,0 +1,628 @@ +/* + + SD - a slightly more friendly wrapper for sdfatlib + + This library aims to expose a subset of SD card functionality + in the form of a higher level "wrapper" object. + + License: GNU General Public License V3 + (Because sdfatlib is licensed with this.) + + (C) Copyright 2010 SparkFun Electronics + + + This library provides four key benefits: + + * Including `SD.h` automatically creates a global + `SD` object which can be interacted with in a similar + manner to other standard global objects like `Serial` and `Ethernet`. + + * Boilerplate initialisation code is contained in one method named + `begin` and no further objects need to be created in order to access + the SD card. + + * Calls to `open` can supply a full path name including parent + directories which simplifies interacting with files in subdirectories. + + * Utility methods are provided to determine whether a file exists + and to create a directory heirarchy. + + + Note however that not all functionality provided by the underlying + sdfatlib library is exposed. + + */ + +/* + + Implementation Notes + + In order to handle multi-directory path traversal, functionality that + requires this ability is implemented as callback functions. + + Individual methods call the `walkPath` function which performs the actual + directory traversal (swapping between two different directory/file handles + along the way) and at each level calls the supplied callback function. + + Some types of functionality will take an action at each level (e.g. exists + or make directory) which others will only take an action at the bottom + level (e.g. open). + + */ + +#include "SD.h" + +namespace SDLib { + +// Used by `getNextPathComponent` +#define MAX_COMPONENT_LEN 12 // What is max length? +#define PATH_COMPONENT_BUFFER_LEN MAX_COMPONENT_LEN+1 + +bool getNextPathComponent(const char *path, unsigned int *p_offset, + char *buffer) { + /* + + Parse individual path components from a path. + + e.g. after repeated calls '/foo/bar/baz' will be split + into 'foo', 'bar', 'baz'. + + This is similar to `strtok()` but copies the component into the + supplied buffer rather than modifying the original string. + + + `buffer` needs to be PATH_COMPONENT_BUFFER_LEN in size. + + `p_offset` needs to point to an integer of the offset at + which the previous path component finished. + + Returns `true` if more components remain. + + Returns `false` if this is the last component. + (This means path ended with 'foo' or 'foo/'.) + + */ + + // TODO: Have buffer local to this function, so we know it's the + // correct length? + + int bufferOffset = 0; + + int offset = *p_offset; + + // Skip root or other separator + if (path[offset] == '/') { + offset++; + } + + // Copy the next next path segment + while (bufferOffset < MAX_COMPONENT_LEN + && (path[offset] != '/') + && (path[offset] != '\0')) { + buffer[bufferOffset++] = path[offset++]; + } + + buffer[bufferOffset] = '\0'; + + // Skip trailing separator so we can determine if this + // is the last component in the path or not. + if (path[offset] == '/') { + offset++; + } + + *p_offset = offset; + + return (path[offset] != '\0'); +} + + + +boolean walkPath(const char *filepath, SdFile& parentDir, + boolean (*callback)(SdFile& parentDir, + const char *filePathComponent, + boolean isLastComponent, + void *object), + void *object = NULL) { + /* + + When given a file path (and parent directory--normally root), + this function traverses the directories in the path and at each + level calls the supplied callback function while also providing + the supplied object for context if required. + + e.g. given the path '/foo/bar/baz' + the callback would be called at the equivalent of + '/foo', '/foo/bar' and '/foo/bar/baz'. + + The implementation swaps between two different directory/file + handles as it traverses the directories and does not use recursion + in an attempt to use memory efficiently. + + If a callback wishes to stop the directory traversal it should + return false--in this case the function will stop the traversal, + tidy up and return false. + + If a directory path doesn't exist at some point this function will + also return false and not subsequently call the callback. + + If a directory path specified is complete, valid and the callback + did not indicate the traversal should be interrupted then this + function will return true. + + */ + + + SdFile subfile1; + SdFile subfile2; + + char buffer[PATH_COMPONENT_BUFFER_LEN]; + + unsigned int offset = 0; + + SdFile *p_parent; + SdFile *p_child; + + SdFile *p_tmp_sdfile; + + p_child = &subfile1; + + p_parent = &parentDir; + + while (true) { + + boolean moreComponents = getNextPathComponent(filepath, &offset, buffer); + + boolean shouldContinue = callback((*p_parent), buffer, !moreComponents, object); + + if (!shouldContinue) { + // TODO: Don't repeat this code? + // If it's one we've created then we + // don't need the parent handle anymore. + if (p_parent != &parentDir) { + (*p_parent).close(); + } + return false; + } + + if (!moreComponents) { + break; + } + + boolean exists = (*p_child).open(*p_parent, buffer, O_RDONLY); + + // If it's one we've created then we + // don't need the parent handle anymore. + if (p_parent != &parentDir) { + (*p_parent).close(); + } + + // Handle case when it doesn't exist and we can't continue... + if (exists) { + // We alternate between two file handles as we go down + // the path. + if (p_parent == &parentDir) { + p_parent = &subfile2; + } + + p_tmp_sdfile = p_parent; + p_parent = p_child; + p_child = p_tmp_sdfile; + } else { + return false; + } + } + + if (p_parent != &parentDir) { + (*p_parent).close(); // TODO: Return/ handle different? + } + + return true; +} + + + +/* + + The callbacks used to implement various functionality follow. + + Each callback is supplied with a parent directory handle, + character string with the name of the current file path component, + a flag indicating if this component is the last in the path and + a pointer to an arbitrary object used for context. + + */ + +boolean callback_pathExists(SdFile& parentDir, const char *filePathComponent, + boolean /* isLastComponent */, void * /* object */) { + /* + + Callback used to determine if a file/directory exists in parent + directory. + + Returns true if file path exists. + + */ + SdFile child; + + boolean exists = child.open(parentDir, filePathComponent, O_RDONLY); + + if (exists) { + child.close(); + } + + return exists; +} + + + +boolean callback_makeDirPath(SdFile& parentDir, const char *filePathComponent, + boolean isLastComponent, void *object) { + /* + + Callback used to create a directory in the parent directory if + it does not already exist. + + Returns true if a directory was created or it already existed. + + */ + boolean result = false; + SdFile child; + + result = callback_pathExists(parentDir, filePathComponent, isLastComponent, object); + if (!result) { + result = child.makeDir(parentDir, filePathComponent); + } + + return result; +} + + + /* + +boolean callback_openPath(SdFile& parentDir, char *filePathComponent, + boolean isLastComponent, void *object) { + + Callback used to open a file specified by a filepath that may + specify one or more directories above it. + + Expects the context object to be an instance of `SDClass` and + will use the `file` property of the instance to open the requested + file/directory with the associated file open mode property. + + Always returns true if the directory traversal hasn't reached the + bottom of the directory heirarchy. + + Returns false once the file has been opened--to prevent the traversal + from descending further. (This may be unnecessary.) + + if (isLastComponent) { + SDClass *p_SD = static_cast(object); + p_SD->file.open(parentDir, filePathComponent, p_SD->fileOpenMode); + if (p_SD->fileOpenMode == FILE_WRITE) { + p_SD->file.seekSet(p_SD->file.fileSize()); + } + // TODO: Return file open result? + return false; + } + return true; +} + */ + + + +boolean callback_remove(SdFile& parentDir, const char *filePathComponent, + boolean isLastComponent, void * /* object */) { + if (isLastComponent) { + return SdFile::remove(parentDir, filePathComponent); + } + return true; +} + +boolean callback_rmdir(SdFile& parentDir, const char *filePathComponent, + boolean isLastComponent, void * /* object */) { + if (isLastComponent) { + SdFile f; + if (!f.open(parentDir, filePathComponent, O_READ)) return false; + return f.rmDir(); + } + return true; +} + + + +/* Implementation of class used to create `SDCard` object. */ + + + +boolean SDClass::begin(uint8_t csPin) { + if(root.isOpen()) root.close(); + + /* + + Performs the initialisation required by the sdfatlib library. + + Return true if initialization succeeds, false otherwise. + + */ + return card.init(SPI_HALF_SPEED, csPin) && + volume.init(card) && + root.openRoot(volume); +} + +boolean SDClass::begin(uint32_t clock, uint8_t csPin) { + if(root.isOpen()) root.close(); + + return card.init(SPI_HALF_SPEED, csPin) && + card.setSpiClock(clock) && + volume.init(card) && + root.openRoot(volume); +} + +//call this when a card is removed. It will allow you to insert and initialise a new card. +void SDClass::end() +{ + root.close(); +} + +// this little helper is used to traverse paths +SdFile SDClass::getParentDir(const char *filepath, int *index) { + // get parent directory + SdFile d1; + SdFile d2; + + d1.openRoot(volume); // start with the mostparent, root! + + // we'll use the pointers to swap between the two objects + SdFile *parent = &d1; + SdFile *subdir = &d2; + + const char *origpath = filepath; + + while (strchr(filepath, '/')) { + + // get rid of leading /'s + if (filepath[0] == '/') { + filepath++; + continue; + } + + if (! strchr(filepath, '/')) { + // it was in the root directory, so leave now + break; + } + + // extract just the name of the next subdirectory + uint8_t idx = strchr(filepath, '/') - filepath; + if (idx > 12) + idx = 12; // dont let them specify long names + char subdirname[13]; + strncpy(subdirname, filepath, idx); + subdirname[idx] = 0; + + // close the subdir (we reuse them) if open + subdir->close(); + if (! subdir->open(parent, subdirname, O_READ)) { + // failed to open one of the subdirectories + return SdFile(); + } + // move forward to the next subdirectory + filepath += idx; + + // we reuse the objects, close it. + parent->close(); + + // swap the pointers + SdFile *t = parent; + parent = subdir; + subdir = t; + } + + *index = (int)(filepath - origpath); + // parent is now the parent diretory of the file! + return *parent; +} + + +File SDClass::open(const char *filepath, uint8_t mode) { + /* + + Open the supplied file path for reading or writing. + + The file content can be accessed via the `file` property of + the `SDClass` object--this property is currently + a standard `SdFile` object from `sdfatlib`. + + Defaults to read only. + + If `write` is true, default action (when `append` is true) is to + append data to the end of the file. + + If `append` is false then the file will be truncated first. + + If the file does not exist and it is opened for writing the file + will be created. + + An attempt to open a file for reading that does not exist is an + error. + + */ + + int pathidx; + + // do the interative search + SdFile parentdir = getParentDir(filepath, &pathidx); + // no more subdirs! + + filepath += pathidx; + + if (! filepath[0]) { + // it was the directory itself! + return File(parentdir, "/"); + } + + // Open the file itself + SdFile file; + + // failed to open a subdir! + if (!parentdir.isOpen()) + return File(); + + if ( ! file.open(parentdir, filepath, mode)) { + return File(); + } + // close the parent + parentdir.close(); + + if ((mode & (O_APPEND | O_WRITE)) == (O_APPEND | O_WRITE)) + file.seekSet(file.fileSize()); + return File(file, filepath); +} + + +/* +File SDClass::open(char *filepath, uint8_t mode) { + // + + Open the supplied file path for reading or writing. + + The file content can be accessed via the `file` property of + the `SDClass` object--this property is currently + a standard `SdFile` object from `sdfatlib`. + + Defaults to read only. + + If `write` is true, default action (when `append` is true) is to + append data to the end of the file. + + If `append` is false then the file will be truncated first. + + If the file does not exist and it is opened for writing the file + will be created. + + An attempt to open a file for reading that does not exist is an + error. + + // + + // TODO: Allow for read&write? (Possibly not, as it requires seek.) + + fileOpenMode = mode; + walkPath(filepath, root, callback_openPath, this); + + return File(); + +} +*/ + + +//boolean SDClass::close() { +// /* +// +// Closes the file opened by the `open` method. +// +// */ +// file.close(); +//} + + +boolean SDClass::exists(const char *filepath) { + /* + + Returns true if the supplied file path exists. + + */ + return walkPath(filepath, root, callback_pathExists); +} + + +//boolean SDClass::exists(char *filepath, SdFile& parentDir) { +// /* +// +// Returns true if the supplied file path rooted at `parentDir` +// exists. +// +// */ +// return walkPath(filepath, parentDir, callback_pathExists); +//} + + +boolean SDClass::mkdir(const char *filepath) { + /* + + Makes a single directory or a heirarchy of directories. + + A rough equivalent to `mkdir -p`. + + */ + return walkPath(filepath, root, callback_makeDirPath); +} + +boolean SDClass::rmdir(const char *filepath) { + /* + + Remove a single directory or a heirarchy of directories. + + A rough equivalent to `rm -rf`. + + */ + return walkPath(filepath, root, callback_rmdir); +} + +boolean SDClass::remove(const char *filepath) { + return walkPath(filepath, root, callback_remove); +} + + +// allows you to recurse into a directory +File File::openNextFile(uint8_t mode) { + dir_t p; + + //Serial.print("\t\treading dir..."); + while (_file->readDir(&p) > 0) { + + // done if past last used entry + if (p.name[0] == DIR_NAME_FREE) { + //Serial.println("end"); + return File(); + } + + // skip deleted entry and entries for . and .. + if (p.name[0] == DIR_NAME_DELETED || p.name[0] == '.') { + //Serial.println("dots"); + continue; + } + + // only list subdirectories and files + if (!DIR_IS_FILE_OR_SUBDIR(&p)) { + //Serial.println("notafile"); + continue; + } + + // print file name with possible blank fill + SdFile f; + char name[13]; + _file->dirName(p, name); + //Serial.print("try to open file "); + //Serial.println(name); + + if (f.open(_file, name, mode)) { + //Serial.println("OK!"); + return File(f, name); + } else { + //Serial.println("ugh"); + return File(); + } + } + + //Serial.println("nothing"); + return File(); +} + +void File::rewindDirectory(void) { + if (isDirectory()) + _file->rewind(); +} + +SDClass SD; + +}; diff --git a/app/testdata/libraries/SD_1.2.1/SD/src/SD.h b/app/testdata/libraries/SD_1.2.1/SD/src/SD.h new file mode 100644 index 000000000..a7f221cff --- /dev/null +++ b/app/testdata/libraries/SD_1.2.1/SD/src/SD.h @@ -0,0 +1,127 @@ +/* + + SD - a slightly more friendly wrapper for sdfatlib + + This library aims to expose a subset of SD card functionality + in the form of a higher level "wrapper" object. + + License: GNU General Public License V3 + (Because sdfatlib is licensed with this.) + + (C) Copyright 2010 SparkFun Electronics + + */ + +#ifndef __SD_H__ +#define __SD_H__ + +#include + +#include +#include + +#define FILE_READ O_READ +#define FILE_WRITE (O_READ | O_WRITE | O_CREAT | O_APPEND) + +namespace SDLib { + +class File : public Stream { + private: + char _name[13]; // our name + SdFile *_file; // underlying file pointer + +public: + File(SdFile f, const char *name); // wraps an underlying SdFile + File(void); // 'empty' constructor + virtual size_t write(uint8_t); + virtual size_t write(const uint8_t *buf, size_t size); + virtual int read(); + virtual int peek(); + virtual int available(); + virtual void flush(); + int read(void *buf, uint16_t nbyte); + boolean seek(uint32_t pos); + uint32_t position(); + uint32_t size(); + void close(); + operator bool(); + char * name(); + + boolean isDirectory(void); + File openNextFile(uint8_t mode = O_RDONLY); + void rewindDirectory(void); + + using Print::write; +}; + +class SDClass { + +private: + // These are required for initialisation and use of sdfatlib + Sd2Card card; + SdVolume volume; + SdFile root; + + // my quick&dirty iterator, should be replaced + SdFile getParentDir(const char *filepath, int *indx); +public: + // This needs to be called to set up the connection to the SD card + // before other methods are used. + boolean begin(uint8_t csPin = SD_CHIP_SELECT_PIN); + boolean begin(uint32_t clock, uint8_t csPin); + + //call this when a card is removed. It will allow you to insert and initialise a new card. + void end(); + + // Open the specified file/directory with the supplied mode (e.g. read or + // write, etc). Returns a File object for interacting with the file. + // Note that currently only one file can be open at a time. + File open(const char *filename, uint8_t mode = FILE_READ); + File open(const String &filename, uint8_t mode = FILE_READ) { return open( filename.c_str(), mode ); } + + // Methods to determine if the requested file path exists. + boolean exists(const char *filepath); + boolean exists(const String &filepath) { return exists(filepath.c_str()); } + + // Create the requested directory heirarchy--if intermediate directories + // do not exist they will be created. + boolean mkdir(const char *filepath); + boolean mkdir(const String &filepath) { return mkdir(filepath.c_str()); } + + // Delete the file. + boolean remove(const char *filepath); + boolean remove(const String &filepath) { return remove(filepath.c_str()); } + + boolean rmdir(const char *filepath); + boolean rmdir(const String &filepath) { return rmdir(filepath.c_str()); } + +private: + + // This is used to determine the mode used to open a file + // it's here because it's the easiest place to pass the + // information through the directory walking function. But + // it's probably not the best place for it. + // It shouldn't be set directly--it is set via the parameters to `open`. + int fileOpenMode; + + friend class File; + friend boolean callback_openPath(SdFile&, const char *, boolean, void *); +}; + +extern SDClass SD; + +}; + +// We enclose File and SD classes in namespace SDLib to avoid conflicts +// with others legacy libraries that redefines File class. + +// This ensure compatibility with sketches that uses only SD library +using namespace SDLib; + +// This allows sketches to use SDLib::File with other libraries (in the +// sketch you must use SDFile instead of File to disambiguate) +typedef SDLib::File SDFile; +typedef SDLib::SDClass SDFileSystemClass; +#define SDFileSystem SDLib::SD + +#endif diff --git a/app/testdata/libraries/SD_1.2.1/SD/src/utility/FatStructs.h b/app/testdata/libraries/SD_1.2.1/SD/src/utility/FatStructs.h new file mode 100644 index 000000000..8a2d9ebcc --- /dev/null +++ b/app/testdata/libraries/SD_1.2.1/SD/src/utility/FatStructs.h @@ -0,0 +1,418 @@ +/* Arduino SdFat Library + * Copyright (C) 2009 by William Greiman + * + * This file is part of the Arduino SdFat 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 SdFat 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; +} __attribute__((packed)); +/** 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; +} __attribute__((packed)); +/** 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]; +} __attribute__((packed)); +/** 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; +} __attribute__((packed)); +//------------------------------------------------------------------------------ +// 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; +} __attribute__((packed)); +//------------------------------------------------------------------------------ +// 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/app/testdata/libraries/SD_1.2.1/SD/src/utility/Sd2Card.cpp b/app/testdata/libraries/SD_1.2.1/SD/src/utility/Sd2Card.cpp new file mode 100644 index 000000000..406f83851 --- /dev/null +++ b/app/testdata/libraries/SD_1.2.1/SD/src/utility/Sd2Card.cpp @@ -0,0 +1,724 @@ +/* Arduino Sd2Card Library + * Copyright (C) 2009 by William Greiman + * + * This file is part of the Arduino Sd2Card 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 Sd2Card Library. If not, see + * . + */ +#define USE_SPI_LIB +#include +#include "Sd2Card.h" +//------------------------------------------------------------------------------ +#ifndef SOFTWARE_SPI +#ifdef USE_SPI_LIB + +#ifndef SDCARD_SPI +#define SDCARD_SPI SPI +#endif + +#include +static SPISettings settings; +#endif +// functions for hardware SPI +/** Send a byte to the card */ +static void spiSend(uint8_t b) { +#ifndef USE_SPI_LIB + SPDR = b; + while (!(SPSR & (1 << SPIF))) + ; +#else + SDCARD_SPI.transfer(b); +#endif +} +/** Receive a byte from the card */ +static uint8_t spiRec(void) { +#ifndef USE_SPI_LIB + spiSend(0XFF); + return SPDR; +#else + return SDCARD_SPI.transfer(0xFF); +#endif +} +#else // SOFTWARE_SPI +//------------------------------------------------------------------------------ +/** nop to tune soft SPI timing */ +#define nop asm volatile ("nop\n\t") +//------------------------------------------------------------------------------ +/** Soft SPI receive */ +uint8_t spiRec(void) { + uint8_t data = 0; + // no interrupts during byte receive - about 8 us + cli(); + // output pin high - like sending 0XFF + fastDigitalWrite(SPI_MOSI_PIN, HIGH); + + for (uint8_t i = 0; i < 8; i++) { + fastDigitalWrite(SPI_SCK_PIN, HIGH); + + // adjust so SCK is nice + nop; + nop; + + data <<= 1; + + if (fastDigitalRead(SPI_MISO_PIN)) data |= 1; + + fastDigitalWrite(SPI_SCK_PIN, LOW); + } + // enable interrupts + sei(); + return data; +} +//------------------------------------------------------------------------------ +/** Soft SPI send */ +void spiSend(uint8_t data) { + // no interrupts during byte send - about 8 us + cli(); + for (uint8_t i = 0; i < 8; i++) { + fastDigitalWrite(SPI_SCK_PIN, LOW); + + fastDigitalWrite(SPI_MOSI_PIN, data & 0X80); + + data <<= 1; + + fastDigitalWrite(SPI_SCK_PIN, HIGH); + } + // hold SCK high for a few ns + nop; + nop; + nop; + nop; + + fastDigitalWrite(SPI_SCK_PIN, LOW); + // enable interrupts + sei(); +} +#endif // SOFTWARE_SPI +//------------------------------------------------------------------------------ +// send command and return error code. Return zero for OK +uint8_t Sd2Card::cardCommand(uint8_t cmd, uint32_t arg) { + // end read if in partialBlockRead mode + readEnd(); + + // select card + chipSelectLow(); + + // wait up to 300 ms if busy + waitNotBusy(300); + + // send command + spiSend(cmd | 0x40); + + // send argument + for (int8_t s = 24; s >= 0; s -= 8) spiSend(arg >> s); + + // send CRC + uint8_t crc = 0XFF; + if (cmd == CMD0) crc = 0X95; // correct crc for CMD0 with arg 0 + if (cmd == CMD8) crc = 0X87; // correct crc for CMD8 with arg 0X1AA + spiSend(crc); + + // wait for response + for (uint8_t i = 0; ((status_ = spiRec()) & 0X80) && i != 0XFF; i++) + ; + return status_; +} +//------------------------------------------------------------------------------ +/** + * Determine the size of an SD flash memory card. + * + * \return The number of 512 byte data blocks in the card + * or zero if an error occurs. + */ +uint32_t Sd2Card::cardSize(void) { + csd_t csd; + if (!readCSD(&csd)) return 0; + if (csd.v1.csd_ver == 0) { + uint8_t read_bl_len = csd.v1.read_bl_len; + uint16_t c_size = (csd.v1.c_size_high << 10) + | (csd.v1.c_size_mid << 2) | csd.v1.c_size_low; + uint8_t c_size_mult = (csd.v1.c_size_mult_high << 1) + | csd.v1.c_size_mult_low; + return (uint32_t)(c_size + 1) << (c_size_mult + read_bl_len - 7); + } else if (csd.v2.csd_ver == 1) { + uint32_t c_size = ((uint32_t)csd.v2.c_size_high << 16) + | (csd.v2.c_size_mid << 8) | csd.v2.c_size_low; + return (c_size + 1) << 10; + } else { + error(SD_CARD_ERROR_BAD_CSD); + return 0; + } +} +//------------------------------------------------------------------------------ +static uint8_t chip_select_asserted = 0; + +void Sd2Card::chipSelectHigh(void) { + digitalWrite(chipSelectPin_, HIGH); +#ifdef USE_SPI_LIB + if (chip_select_asserted) { + chip_select_asserted = 0; + SDCARD_SPI.endTransaction(); + } +#endif +} +//------------------------------------------------------------------------------ +void Sd2Card::chipSelectLow(void) { +#ifdef USE_SPI_LIB + if (!chip_select_asserted) { + chip_select_asserted = 1; + SDCARD_SPI.beginTransaction(settings); + } +#endif + digitalWrite(chipSelectPin_, LOW); +} +//------------------------------------------------------------------------------ +/** Erase a range of blocks. + * + * \param[in] firstBlock The address of the first block in the range. + * \param[in] lastBlock The address of the last block in the range. + * + * \note This function requests the SD card to do a flash erase for a + * range of blocks. The data on the card after an erase operation is + * either 0 or 1, depends on the card vendor. The card must support + * single block erase. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +uint8_t Sd2Card::erase(uint32_t firstBlock, uint32_t lastBlock) { + if (!eraseSingleBlockEnable()) { + error(SD_CARD_ERROR_ERASE_SINGLE_BLOCK); + goto fail; + } + if (type_ != SD_CARD_TYPE_SDHC) { + firstBlock <<= 9; + lastBlock <<= 9; + } + if (cardCommand(CMD32, firstBlock) + || cardCommand(CMD33, lastBlock) + || cardCommand(CMD38, 0)) { + error(SD_CARD_ERROR_ERASE); + goto fail; + } + if (!waitNotBusy(SD_ERASE_TIMEOUT)) { + error(SD_CARD_ERROR_ERASE_TIMEOUT); + goto fail; + } + chipSelectHigh(); + return true; + + fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** Determine if card supports single block erase. + * + * \return The value one, true, is returned if single block erase is supported. + * The value zero, false, is returned if single block erase is not supported. + */ +uint8_t Sd2Card::eraseSingleBlockEnable(void) { + csd_t csd; + return readCSD(&csd) ? csd.v1.erase_blk_en : 0; +} +//------------------------------------------------------------------------------ +/** + * Initialize an SD flash memory card. + * + * \param[in] sckRateID SPI clock rate selector. See setSckRate(). + * \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. The reason for failure + * can be determined by calling errorCode() and errorData(). + */ +uint8_t Sd2Card::init(uint8_t sckRateID, uint8_t chipSelectPin) { + errorCode_ = inBlock_ = partialBlockRead_ = type_ = 0; + chipSelectPin_ = chipSelectPin; + // 16-bit init start time allows over a minute + unsigned int t0 = millis(); + uint32_t arg; + + // set pin modes + pinMode(chipSelectPin_, OUTPUT); + digitalWrite(chipSelectPin_, HIGH); +#ifndef USE_SPI_LIB + pinMode(SPI_MISO_PIN, INPUT); + pinMode(SPI_MOSI_PIN, OUTPUT); + pinMode(SPI_SCK_PIN, OUTPUT); +#endif + +#ifndef SOFTWARE_SPI +#ifndef USE_SPI_LIB + // SS must be in output mode even it is not chip select + pinMode(SS_PIN, OUTPUT); + digitalWrite(SS_PIN, HIGH); // disable any SPI device using hardware SS pin + // Enable SPI, Master, clock rate f_osc/128 + SPCR = (1 << SPE) | (1 << MSTR) | (1 << SPR1) | (1 << SPR0); + // clear double speed + SPSR &= ~(1 << SPI2X); +#else // USE_SPI_LIB + SDCARD_SPI.begin(); + settings = SPISettings(250000, MSBFIRST, SPI_MODE0); +#endif // USE_SPI_LIB +#endif // SOFTWARE_SPI + + // must supply min of 74 clock cycles with CS high. +#ifdef USE_SPI_LIB + SDCARD_SPI.beginTransaction(settings); +#endif + for (uint8_t i = 0; i < 10; i++) spiSend(0XFF); +#ifdef USE_SPI_LIB + SDCARD_SPI.endTransaction(); +#endif + + chipSelectLow(); + + // command to go idle in SPI mode + while ((status_ = cardCommand(CMD0, 0)) != R1_IDLE_STATE) { + unsigned int d = millis() - t0; + if (d > SD_INIT_TIMEOUT) { + error(SD_CARD_ERROR_CMD0); + goto fail; + } + } + // check SD version + if ((cardCommand(CMD8, 0x1AA) & R1_ILLEGAL_COMMAND)) { + type(SD_CARD_TYPE_SD1); + } else { + // only need last byte of r7 response + for (uint8_t i = 0; i < 4; i++) status_ = spiRec(); + if (status_ != 0XAA) { + error(SD_CARD_ERROR_CMD8); + goto fail; + } + type(SD_CARD_TYPE_SD2); + } + // initialize card and send host supports SDHC if SD2 + arg = type() == SD_CARD_TYPE_SD2 ? 0X40000000 : 0; + + while ((status_ = cardAcmd(ACMD41, arg)) != R1_READY_STATE) { + // check for timeout + unsigned int d = millis() - t0; + if (d > SD_INIT_TIMEOUT) { + error(SD_CARD_ERROR_ACMD41); + goto fail; + } + } + // if SD2 read OCR register to check for SDHC card + if (type() == SD_CARD_TYPE_SD2) { + if (cardCommand(CMD58, 0)) { + error(SD_CARD_ERROR_CMD58); + goto fail; + } + if ((spiRec() & 0XC0) == 0XC0) type(SD_CARD_TYPE_SDHC); + // discard rest of ocr - contains allowed voltage range + for (uint8_t i = 0; i < 3; i++) spiRec(); + } + chipSelectHigh(); + +#ifndef SOFTWARE_SPI + return setSckRate(sckRateID); +#else // SOFTWARE_SPI + return true; +#endif // SOFTWARE_SPI + + fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** + * Enable or disable partial block reads. + * + * Enabling partial block reads improves performance by allowing a block + * to be read over the SPI bus as several sub-blocks. Errors may occur + * if the time between reads is too long since the SD card may timeout. + * The SPI SS line will be held low until the entire block is read or + * readEnd() is called. + * + * Use this for applications like the Adafruit Wave Shield. + * + * \param[in] value The value TRUE (non-zero) or FALSE (zero).) + */ +void Sd2Card::partialBlockRead(uint8_t value) { + readEnd(); + partialBlockRead_ = value; +} +//------------------------------------------------------------------------------ +/** + * Read a 512 byte block from an SD card device. + * + * \param[in] block 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 Sd2Card::readBlock(uint32_t block, uint8_t* dst) { + return readData(block, 0, 512, dst); +} +//------------------------------------------------------------------------------ +/** + * Read part of a 512 byte block from an SD card. + * + * \param[in] block Logical block to be read. + * \param[in] offset Number of bytes to skip at start of block + * \param[out] dst Pointer to the location that will receive the data. + * \param[in] count Number of bytes to read + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +uint8_t Sd2Card::readData(uint32_t block, + uint16_t offset, uint16_t count, uint8_t* dst) { + if (count == 0) return true; + if ((count + offset) > 512) { + goto fail; + } + if (!inBlock_ || block != block_ || offset < offset_) { + block_ = block; + // use address if not SDHC card + if (type()!= SD_CARD_TYPE_SDHC) block <<= 9; + if (cardCommand(CMD17, block)) { + error(SD_CARD_ERROR_CMD17); + goto fail; + } + if (!waitStartBlock()) { + goto fail; + } + offset_ = 0; + inBlock_ = 1; + } + +#ifdef OPTIMIZE_HARDWARE_SPI + // start first spi transfer + SPDR = 0XFF; + + // skip data before offset + for (;offset_ < offset; offset_++) { + while (!(SPSR & (1 << SPIF))) + ; + SPDR = 0XFF; + } + // transfer data + n = count - 1; + for (uint16_t i = 0; i < n; i++) { + while (!(SPSR & (1 << SPIF))) + ; + dst[i] = SPDR; + SPDR = 0XFF; + } + // wait for last byte + while (!(SPSR & (1 << SPIF))) + ; + dst[n] = SPDR; + +#else // OPTIMIZE_HARDWARE_SPI + + // skip data before offset + for (;offset_ < offset; offset_++) { + spiRec(); + } + // transfer data + for (uint16_t i = 0; i < count; i++) { + dst[i] = spiRec(); + } +#endif // OPTIMIZE_HARDWARE_SPI + + offset_ += count; + if (!partialBlockRead_ || offset_ >= 512) { + // read rest of data, checksum and set chip select high + readEnd(); + } + return true; + + fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** Skip remaining data in a block when in partial block read mode. */ +void Sd2Card::readEnd(void) { + if (inBlock_) { + // skip data and crc +#ifdef OPTIMIZE_HARDWARE_SPI + // optimize skip for hardware + SPDR = 0XFF; + while (offset_++ < 513) { + while (!(SPSR & (1 << SPIF))) + ; + SPDR = 0XFF; + } + // wait for last crc byte + while (!(SPSR & (1 << SPIF))) + ; +#else // OPTIMIZE_HARDWARE_SPI + while (offset_++ < 514) spiRec(); +#endif // OPTIMIZE_HARDWARE_SPI + chipSelectHigh(); + inBlock_ = 0; + } +} +//------------------------------------------------------------------------------ +/** read CID or CSR register */ +uint8_t Sd2Card::readRegister(uint8_t cmd, void* buf) { + uint8_t* dst = reinterpret_cast(buf); + if (cardCommand(cmd, 0)) { + error(SD_CARD_ERROR_READ_REG); + goto fail; + } + if (!waitStartBlock()) goto fail; + // transfer data + for (uint16_t i = 0; i < 16; i++) dst[i] = spiRec(); + spiRec(); // get first crc byte + spiRec(); // get second crc byte + chipSelectHigh(); + return true; + + fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** + * Set the SPI clock rate. + * + * \param[in] sckRateID A value in the range [0, 6]. + * + * The SPI clock will be set to F_CPU/pow(2, 1 + sckRateID). The maximum + * SPI rate is F_CPU/2 for \a sckRateID = 0 and the minimum rate is F_CPU/128 + * for \a scsRateID = 6. + * + * \return The value one, true, is returned for success and the value zero, + * false, is returned for an invalid value of \a sckRateID. + */ +uint8_t Sd2Card::setSckRate(uint8_t sckRateID) { + if (sckRateID > 6) { + error(SD_CARD_ERROR_SCK_RATE); + return false; + } +#ifndef USE_SPI_LIB + // see avr processor datasheet for SPI register bit definitions + if ((sckRateID & 1) || sckRateID == 6) { + SPSR &= ~(1 << SPI2X); + } else { + SPSR |= (1 << SPI2X); + } + SPCR &= ~((1 < SD_READ_TIMEOUT) { + error(SD_CARD_ERROR_READ_TIMEOUT); + goto fail; + } + } + if (status_ != DATA_START_BLOCK) { + error(SD_CARD_ERROR_READ); + goto fail; + } + return true; + + fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** + * Writes a 512 byte block to an SD card. + * + * \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 Sd2Card::writeBlock(uint32_t blockNumber, const uint8_t* src) { +#if SD_PROTECT_BLOCK_ZERO + // don't allow write to first block + if (blockNumber == 0) { + error(SD_CARD_ERROR_WRITE_BLOCK_ZERO); + goto fail; + } +#endif // SD_PROTECT_BLOCK_ZERO + + // use address if not SDHC card + if (type() != SD_CARD_TYPE_SDHC) blockNumber <<= 9; + if (cardCommand(CMD24, blockNumber)) { + error(SD_CARD_ERROR_CMD24); + goto fail; + } + if (!writeData(DATA_START_BLOCK, src)) goto fail; + + // wait for flash programming to complete + if (!waitNotBusy(SD_WRITE_TIMEOUT)) { + error(SD_CARD_ERROR_WRITE_TIMEOUT); + goto fail; + } + // response is r2 so get and check two bytes for nonzero + if (cardCommand(CMD13, 0) || spiRec()) { + error(SD_CARD_ERROR_WRITE_PROGRAMMING); + goto fail; + } + chipSelectHigh(); + return true; + + fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** Write one data block in a multiple block write sequence */ +uint8_t Sd2Card::writeData(const uint8_t* src) { + // wait for previous write to finish + if (!waitNotBusy(SD_WRITE_TIMEOUT)) { + error(SD_CARD_ERROR_WRITE_MULTIPLE); + chipSelectHigh(); + return false; + } + return writeData(WRITE_MULTIPLE_TOKEN, src); +} +//------------------------------------------------------------------------------ +// send one block of data for write block or write multiple blocks +uint8_t Sd2Card::writeData(uint8_t token, const uint8_t* src) { +#ifdef OPTIMIZE_HARDWARE_SPI + + // send data - optimized loop + SPDR = token; + + // send two byte per iteration + for (uint16_t i = 0; i < 512; i += 2) { + while (!(SPSR & (1 << SPIF))) + ; + SPDR = src[i]; + while (!(SPSR & (1 << SPIF))) + ; + SPDR = src[i+1]; + } + + // wait for last data byte + while (!(SPSR & (1 << SPIF))) + ; + +#else // OPTIMIZE_HARDWARE_SPI + spiSend(token); + for (uint16_t i = 0; i < 512; i++) { + spiSend(src[i]); + } +#endif // OPTIMIZE_HARDWARE_SPI + spiSend(0xff); // dummy crc + spiSend(0xff); // dummy crc + + status_ = spiRec(); + if ((status_ & DATA_RES_MASK) != DATA_RES_ACCEPTED) { + error(SD_CARD_ERROR_WRITE); + chipSelectHigh(); + return false; + } + return true; +} +//------------------------------------------------------------------------------ +/** Start a write multiple blocks sequence. + * + * \param[in] blockNumber Address of first block in sequence. + * \param[in] eraseCount The number of blocks to be pre-erased. + * + * \note This function is used with writeData() and writeStop() + * for optimized multiple block writes. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +uint8_t Sd2Card::writeStart(uint32_t blockNumber, uint32_t eraseCount) { +#if SD_PROTECT_BLOCK_ZERO + // don't allow write to first block + if (blockNumber == 0) { + error(SD_CARD_ERROR_WRITE_BLOCK_ZERO); + goto fail; + } +#endif // SD_PROTECT_BLOCK_ZERO + // send pre-erase count + if (cardAcmd(ACMD23, eraseCount)) { + error(SD_CARD_ERROR_ACMD23); + goto fail; + } + // use address if not SDHC card + if (type() != SD_CARD_TYPE_SDHC) blockNumber <<= 9; + if (cardCommand(CMD25, blockNumber)) { + error(SD_CARD_ERROR_CMD25); + goto fail; + } + return true; + + fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** End a write multiple blocks sequence. + * +* \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +uint8_t Sd2Card::writeStop(void) { + if (!waitNotBusy(SD_WRITE_TIMEOUT)) goto fail; + spiSend(STOP_TRAN_TOKEN); + if (!waitNotBusy(SD_WRITE_TIMEOUT)) goto fail; + chipSelectHigh(); + return true; + + fail: + error(SD_CARD_ERROR_STOP_TRAN); + chipSelectHigh(); + return false; +} diff --git a/app/testdata/libraries/SD_1.2.1/SD/src/utility/Sd2Card.h b/app/testdata/libraries/SD_1.2.1/SD/src/utility/Sd2Card.h new file mode 100644 index 000000000..9c3faff6e --- /dev/null +++ b/app/testdata/libraries/SD_1.2.1/SD/src/utility/Sd2Card.h @@ -0,0 +1,260 @@ +/* Arduino Sd2Card Library + * Copyright (C) 2009 by William Greiman + * + * This file is part of the Arduino Sd2Card 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 Sd2Card Library. If not, see + * . + */ +#ifndef Sd2Card_h +#define Sd2Card_h +/** + * \file + * Sd2Card class + */ +#include "Sd2PinMap.h" +#include "SdInfo.h" +/** Set SCK to max rate of F_CPU/2. See Sd2Card::setSckRate(). */ +uint8_t const SPI_FULL_SPEED = 0; +/** Set SCK rate to F_CPU/4. See Sd2Card::setSckRate(). */ +uint8_t const SPI_HALF_SPEED = 1; +/** Set SCK rate to F_CPU/8. Sd2Card::setSckRate(). */ +uint8_t const SPI_QUARTER_SPEED = 2; +/** + * USE_SPI_LIB: if set, use the SPI library bundled with Arduino IDE, otherwise + * run with a standalone driver for AVR. + */ +#define USE_SPI_LIB +/** + * Define MEGA_SOFT_SPI non-zero to use software SPI on Mega Arduinos. + * Pins used are SS 10, MOSI 11, MISO 12, and SCK 13. + * + * MEGA_SOFT_SPI allows an unmodified Adafruit GPS Shield to be used + * on Mega Arduinos. Software SPI works well with GPS Shield V1.1 + * but many SD cards will fail with GPS Shield V1.0. + */ +#define MEGA_SOFT_SPI 0 +//------------------------------------------------------------------------------ +#if MEGA_SOFT_SPI && (defined(__AVR_ATmega1280__)||defined(__AVR_ATmega2560__)) +#define SOFTWARE_SPI +#endif // MEGA_SOFT_SPI +//------------------------------------------------------------------------------ +// SPI pin definitions +// +#ifndef SOFTWARE_SPI +// hardware pin defs + +// include pins_arduino.h or variant.h depending on architecture, via Arduino.h +#include + +/** + * SD Chip Select pin + * + * Warning if this pin is redefined the hardware SS will 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. + */ +#ifndef SDCARD_SS_PIN +/** The default chip select pin for the SD card is SS. */ +uint8_t const SD_CHIP_SELECT_PIN = SS; +#else +uint8_t const SD_CHIP_SELECT_PIN = SDCARD_SS_PIN; +#endif + +// The following three pins must not be redefined for hardware SPI, +// so ensure that they are taken from pins_arduino.h or variant.h, depending on architecture. +#ifndef SDCARD_MOSI_PIN +/** SPI Master Out Slave In pin */ +uint8_t const SPI_MOSI_PIN = MOSI; +/** SPI Master In Slave Out pin */ +uint8_t const SPI_MISO_PIN = MISO; +/** SPI Clock pin */ +uint8_t const SPI_SCK_PIN = SCK; +#else +uint8_t const SPI_MOSI_PIN = SDCARD_MOSI_PIN; +uint8_t const SPI_MISO_PIN = SDCARD_MISO_PIN; +uint8_t const SPI_SCK_PIN = SDCARD_SCK_PIN; +#endif + +/** optimize loops for hardware SPI */ +#ifndef USE_SPI_LIB +#define OPTIMIZE_HARDWARE_SPI +#endif + +#else // SOFTWARE_SPI +// define software SPI pins so Mega can use unmodified GPS Shield +/** SPI chip select pin */ +uint8_t const SD_CHIP_SELECT_PIN = 10; +/** SPI Master Out Slave In pin */ +uint8_t const SPI_MOSI_PIN = 11; +/** SPI Master In Slave Out pin */ +uint8_t const SPI_MISO_PIN = 12; +/** SPI Clock pin */ +uint8_t const SPI_SCK_PIN = 13; +#endif // SOFTWARE_SPI +//------------------------------------------------------------------------------ +/** Protect block zero from write if nonzero */ +#define SD_PROTECT_BLOCK_ZERO 1 +/** init timeout ms */ +unsigned int const SD_INIT_TIMEOUT = 2000; +/** erase timeout ms */ +unsigned int const SD_ERASE_TIMEOUT = 10000; +/** read timeout ms */ +unsigned int const SD_READ_TIMEOUT = 300; +/** write time out ms */ +unsigned int const SD_WRITE_TIMEOUT = 600; +//------------------------------------------------------------------------------ +// SD card errors +/** timeout error for command CMD0 */ +uint8_t const SD_CARD_ERROR_CMD0 = 0X1; +/** CMD8 was not accepted - not a valid SD card*/ +uint8_t const SD_CARD_ERROR_CMD8 = 0X2; +/** card returned an error response for CMD17 (read block) */ +uint8_t const SD_CARD_ERROR_CMD17 = 0X3; +/** card returned an error response for CMD24 (write block) */ +uint8_t const SD_CARD_ERROR_CMD24 = 0X4; +/** WRITE_MULTIPLE_BLOCKS command failed */ +uint8_t const SD_CARD_ERROR_CMD25 = 0X05; +/** card returned an error response for CMD58 (read OCR) */ +uint8_t const SD_CARD_ERROR_CMD58 = 0X06; +/** SET_WR_BLK_ERASE_COUNT failed */ +uint8_t const SD_CARD_ERROR_ACMD23 = 0X07; +/** card's ACMD41 initialization process timeout */ +uint8_t const SD_CARD_ERROR_ACMD41 = 0X08; +/** card returned a bad CSR version field */ +uint8_t const SD_CARD_ERROR_BAD_CSD = 0X09; +/** erase block group command failed */ +uint8_t const SD_CARD_ERROR_ERASE = 0X0A; +/** card not capable of single block erase */ +uint8_t const SD_CARD_ERROR_ERASE_SINGLE_BLOCK = 0X0B; +/** Erase sequence timed out */ +uint8_t const SD_CARD_ERROR_ERASE_TIMEOUT = 0X0C; +/** card returned an error token instead of read data */ +uint8_t const SD_CARD_ERROR_READ = 0X0D; +/** read CID or CSD failed */ +uint8_t const SD_CARD_ERROR_READ_REG = 0X0E; +/** timeout while waiting for start of read data */ +uint8_t const SD_CARD_ERROR_READ_TIMEOUT = 0X0F; +/** card did not accept STOP_TRAN_TOKEN */ +uint8_t const SD_CARD_ERROR_STOP_TRAN = 0X10; +/** card returned an error token as a response to a write operation */ +uint8_t const SD_CARD_ERROR_WRITE = 0X11; +/** attempt to write protected block zero */ +uint8_t const SD_CARD_ERROR_WRITE_BLOCK_ZERO = 0X12; +/** card did not go ready for a multiple block write */ +uint8_t const SD_CARD_ERROR_WRITE_MULTIPLE = 0X13; +/** card returned an error to a CMD13 status check after a write */ +uint8_t const SD_CARD_ERROR_WRITE_PROGRAMMING = 0X14; +/** timeout occurred during write programming */ +uint8_t const SD_CARD_ERROR_WRITE_TIMEOUT = 0X15; +/** incorrect rate selected */ +uint8_t const SD_CARD_ERROR_SCK_RATE = 0X16; +//------------------------------------------------------------------------------ +// card types +/** Standard capacity V1 SD card */ +uint8_t const SD_CARD_TYPE_SD1 = 1; +/** Standard capacity V2 SD card */ +uint8_t const SD_CARD_TYPE_SD2 = 2; +/** High Capacity SD card */ +uint8_t const SD_CARD_TYPE_SDHC = 3; +//------------------------------------------------------------------------------ +/** + * \class Sd2Card + * \brief Raw access to SD and SDHC flash memory cards. + */ +class Sd2Card { + public: + /** Construct an instance of Sd2Card. */ + Sd2Card(void) : errorCode_(0), inBlock_(0), partialBlockRead_(0), type_(0) {} + uint32_t cardSize(void); + uint8_t erase(uint32_t firstBlock, uint32_t lastBlock); + uint8_t eraseSingleBlockEnable(void); + /** + * \return error code for last error. See Sd2Card.h for a list of error codes. + */ + uint8_t errorCode(void) const {return errorCode_;} + /** \return error data for last error. */ + uint8_t errorData(void) const {return status_;} + /** + * Initialize an SD flash memory card with default clock rate and chip + * select pin. See sd2Card::init(uint8_t sckRateID, uint8_t chipSelectPin). + */ + uint8_t init(void) { + return init(SPI_FULL_SPEED, SD_CHIP_SELECT_PIN); + } + /** + * Initialize an SD flash memory card with the selected SPI clock rate + * and the default SD chip select pin. + * See sd2Card::init(uint8_t sckRateID, uint8_t chipSelectPin). + */ + uint8_t init(uint8_t sckRateID) { + return init(sckRateID, SD_CHIP_SELECT_PIN); + } + uint8_t init(uint8_t sckRateID, uint8_t chipSelectPin); + void partialBlockRead(uint8_t value); + /** Returns the current value, true or false, for partial block read. */ + uint8_t partialBlockRead(void) const {return partialBlockRead_;} + uint8_t readBlock(uint32_t block, uint8_t* dst); + uint8_t readData(uint32_t block, + uint16_t offset, uint16_t count, uint8_t* dst); + /** + * Read a cards CID register. The CID contains card identification + * information such as Manufacturer ID, Product name, Product serial + * number and Manufacturing date. */ + uint8_t readCID(cid_t* cid) { + return readRegister(CMD10, cid); + } + /** + * Read a cards CSD register. The CSD contains Card-Specific Data that + * provides information regarding access to the card's contents. */ + uint8_t readCSD(csd_t* csd) { + return readRegister(CMD9, csd); + } + void readEnd(void); + uint8_t setSckRate(uint8_t sckRateID); +#ifdef USE_SPI_LIB + uint8_t setSpiClock(uint32_t clock); +#endif + /** Return the card type: SD V1, SD V2 or SDHC */ + uint8_t type(void) const {return type_;} + uint8_t writeBlock(uint32_t blockNumber, const uint8_t* src); + uint8_t writeData(const uint8_t* src); + uint8_t writeStart(uint32_t blockNumber, uint32_t eraseCount); + uint8_t writeStop(void); + private: + uint32_t block_; + uint8_t chipSelectPin_; + uint8_t errorCode_; + uint8_t inBlock_; + uint16_t offset_; + uint8_t partialBlockRead_; + uint8_t status_; + uint8_t type_; + // private functions + uint8_t cardAcmd(uint8_t cmd, uint32_t arg) { + cardCommand(CMD55, 0); + return cardCommand(cmd, arg); + } + uint8_t cardCommand(uint8_t cmd, uint32_t arg); + void error(uint8_t code) {errorCode_ = code;} + uint8_t readRegister(uint8_t cmd, void* buf); + uint8_t sendWriteCommand(uint32_t blockNumber, uint32_t eraseCount); + void chipSelectHigh(void); + void chipSelectLow(void); + void type(uint8_t value) {type_ = value;} + uint8_t waitNotBusy(unsigned int timeoutMillis); + uint8_t writeData(uint8_t token, const uint8_t* src); + uint8_t waitStartBlock(void); +}; +#endif // Sd2Card_h diff --git a/app/testdata/libraries/SD_1.2.1/SD/src/utility/Sd2PinMap.h b/app/testdata/libraries/SD_1.2.1/SD/src/utility/Sd2PinMap.h new file mode 100644 index 000000000..3e2df439a --- /dev/null +++ b/app/testdata/libraries/SD_1.2.1/SD/src/utility/Sd2PinMap.h @@ -0,0 +1,511 @@ +/* Arduino SdFat Library + * Copyright (C) 2010 by William Greiman + * + * This file is part of the Arduino SdFat 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 SdFat Library. If not, see + * . + */ +#if defined(__arm__) // Arduino Due Board follows + +#ifndef Sd2PinMap_h +#define Sd2PinMap_h + +#include + +uint8_t const SS_PIN = SS; +uint8_t const MOSI_PIN = MOSI; +uint8_t const MISO_PIN = MISO; +uint8_t const SCK_PIN = SCK; + +#endif // Sd2PinMap_h + +#elif defined(__AVR__) // Other AVR based Boards follows + +// Warning this file was generated by a program. +#ifndef Sd2PinMap_h +#define Sd2PinMap_h +#include + +//------------------------------------------------------------------------------ +/** struct for mapping digital pins */ +struct pin_map_t { + volatile uint8_t* ddr; + volatile uint8_t* pin; + volatile uint8_t* port; + uint8_t bit; +}; +//------------------------------------------------------------------------------ +#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) +// Mega + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 20; +uint8_t const SCL_PIN = 21; + +// SPI port +uint8_t const SS_PIN = 53; +uint8_t const MOSI_PIN = 51; +uint8_t const MISO_PIN = 50; +uint8_t const SCK_PIN = 52; + +static const pin_map_t digitalPinMap[] = { + {&DDRE, &PINE, &PORTE, 0}, // E0 0 + {&DDRE, &PINE, &PORTE, 1}, // E1 1 + {&DDRE, &PINE, &PORTE, 4}, // E4 2 + {&DDRE, &PINE, &PORTE, 5}, // E5 3 + {&DDRG, &PING, &PORTG, 5}, // G5 4 + {&DDRE, &PINE, &PORTE, 3}, // E3 5 + {&DDRH, &PINH, &PORTH, 3}, // H3 6 + {&DDRH, &PINH, &PORTH, 4}, // H4 7 + {&DDRH, &PINH, &PORTH, 5}, // H5 8 + {&DDRH, &PINH, &PORTH, 6}, // H6 9 + {&DDRB, &PINB, &PORTB, 4}, // B4 10 + {&DDRB, &PINB, &PORTB, 5}, // B5 11 + {&DDRB, &PINB, &PORTB, 6}, // B6 12 + {&DDRB, &PINB, &PORTB, 7}, // B7 13 + {&DDRJ, &PINJ, &PORTJ, 1}, // J1 14 + {&DDRJ, &PINJ, &PORTJ, 0}, // J0 15 + {&DDRH, &PINH, &PORTH, 1}, // H1 16 + {&DDRH, &PINH, &PORTH, 0}, // H0 17 + {&DDRD, &PIND, &PORTD, 3}, // D3 18 + {&DDRD, &PIND, &PORTD, 2}, // D2 19 + {&DDRD, &PIND, &PORTD, 1}, // D1 20 + {&DDRD, &PIND, &PORTD, 0}, // D0 21 + {&DDRA, &PINA, &PORTA, 0}, // A0 22 + {&DDRA, &PINA, &PORTA, 1}, // A1 23 + {&DDRA, &PINA, &PORTA, 2}, // A2 24 + {&DDRA, &PINA, &PORTA, 3}, // A3 25 + {&DDRA, &PINA, &PORTA, 4}, // A4 26 + {&DDRA, &PINA, &PORTA, 5}, // A5 27 + {&DDRA, &PINA, &PORTA, 6}, // A6 28 + {&DDRA, &PINA, &PORTA, 7}, // A7 29 + {&DDRC, &PINC, &PORTC, 7}, // C7 30 + {&DDRC, &PINC, &PORTC, 6}, // C6 31 + {&DDRC, &PINC, &PORTC, 5}, // C5 32 + {&DDRC, &PINC, &PORTC, 4}, // C4 33 + {&DDRC, &PINC, &PORTC, 3}, // C3 34 + {&DDRC, &PINC, &PORTC, 2}, // C2 35 + {&DDRC, &PINC, &PORTC, 1}, // C1 36 + {&DDRC, &PINC, &PORTC, 0}, // C0 37 + {&DDRD, &PIND, &PORTD, 7}, // D7 38 + {&DDRG, &PING, &PORTG, 2}, // G2 39 + {&DDRG, &PING, &PORTG, 1}, // G1 40 + {&DDRG, &PING, &PORTG, 0}, // G0 41 + {&DDRL, &PINL, &PORTL, 7}, // L7 42 + {&DDRL, &PINL, &PORTL, 6}, // L6 43 + {&DDRL, &PINL, &PORTL, 5}, // L5 44 + {&DDRL, &PINL, &PORTL, 4}, // L4 45 + {&DDRL, &PINL, &PORTL, 3}, // L3 46 + {&DDRL, &PINL, &PORTL, 2}, // L2 47 + {&DDRL, &PINL, &PORTL, 1}, // L1 48 + {&DDRL, &PINL, &PORTL, 0}, // L0 49 + {&DDRB, &PINB, &PORTB, 3}, // B3 50 + {&DDRB, &PINB, &PORTB, 2}, // B2 51 + {&DDRB, &PINB, &PORTB, 1}, // B1 52 + {&DDRB, &PINB, &PORTB, 0}, // B0 53 + {&DDRF, &PINF, &PORTF, 0}, // F0 54 + {&DDRF, &PINF, &PORTF, 1}, // F1 55 + {&DDRF, &PINF, &PORTF, 2}, // F2 56 + {&DDRF, &PINF, &PORTF, 3}, // F3 57 + {&DDRF, &PINF, &PORTF, 4}, // F4 58 + {&DDRF, &PINF, &PORTF, 5}, // F5 59 + {&DDRF, &PINF, &PORTF, 6}, // F6 60 + {&DDRF, &PINF, &PORTF, 7}, // F7 61 + {&DDRK, &PINK, &PORTK, 0}, // K0 62 + {&DDRK, &PINK, &PORTK, 1}, // K1 63 + {&DDRK, &PINK, &PORTK, 2}, // K2 64 + {&DDRK, &PINK, &PORTK, 3}, // K3 65 + {&DDRK, &PINK, &PORTK, 4}, // K4 66 + {&DDRK, &PINK, &PORTK, 5}, // K5 67 + {&DDRK, &PINK, &PORTK, 6}, // K6 68 + {&DDRK, &PINK, &PORTK, 7} // K7 69 +}; +//------------------------------------------------------------------------------ +#elif (defined(__AVR_ATmega644P__) || defined(__AVR_ATmega1284P__)) && defined(CORE_MICRODUINO) +// Microduino Core+ + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 20; +uint8_t const SCL_PIN = 21; + +// SPI port +uint8_t const SS_PIN = 10; +uint8_t const MOSI_PIN = 11; +uint8_t const MISO_PIN = 12; +uint8_t const SCK_PIN = 13; + +static const pin_map_t digitalPinMap[] = { + {&DDRD, &PIND, &PORTD, 0}, // D0 PD0 + {&DDRD, &PIND, &PORTD, 1}, // D1 PD1 + {&DDRD, &PIND, &PORTD, 2}, // D2 PD2 + {&DDRD, &PIND, &PORTD, 3}, // D3 PD3 + {&DDRB, &PINB, &PORTB, 0}, // D4 PB0 + {&DDRB, &PINB, &PORTB, 1}, // D5 PB1 + {&DDRB, &PINB, &PORTB, 2}, // D6 PB2 + {&DDRB, &PINB, &PORTB, 3}, // D7 PB3 + {&DDRD, &PIND, &PORTD, 6}, // D8 PD6 + {&DDRD, &PIND, &PORTD, 5}, // D9 PD5 + {&DDRB, &PINB, &PORTB, 4}, // D10 PB4 + {&DDRB, &PINB, &PORTB, 5}, // D11 PB5 + {&DDRB, &PINB, &PORTB, 6}, // D12 PB6 + {&DDRB, &PINB, &PORTB, 7}, // D13 PB7 + {&DDRC, &PINC, &PORTC, 7}, // D14 PC7 + {&DDRC, &PINC, &PORTC, 6}, // D15 PC6 + {&DDRC, &PINC, &PORTC, 5}, // D16 PC5 + {&DDRC, &PINC, &PORTC, 4}, // D17 PC4 + {&DDRC, &PINC, &PORTC, 3}, // D18 PC3 + {&DDRC, &PINC, &PORTC, 2}, // D19 PC2 + {&DDRC, &PINC, &PORTC, 1}, // D20 PC1 + {&DDRC, &PINC, &PORTC, 0}, // D21 PC0 + {&DDRD, &PIND, &PORTD, 4}, // D22 PD4 + {&DDRD, &PIND, &PORTD, 7}, // D23 PD7 + {&DDRA, &PINA, &PORTA, 7}, // D24 PA7 + {&DDRA, &PINA, &PORTA, 6}, // D25 PA6 + {&DDRA, &PINA, &PORTA, 5}, // D26 PA5 + {&DDRA, &PINA, &PORTA, 4}, // D27 PA4 + {&DDRA, &PINA, &PORTA, 3}, // D28 PA3 + {&DDRA, &PINA, &PORTA, 2}, // D29 PA2 + {&DDRA, &PINA, &PORTA, 1}, // D30 PA1 + {&DDRA, &PINA, &PORTA, 0} // D31 PA0 +}; +//------------------------------------------------------------------------------ +#elif defined(__AVR_ATmega128RFA1__) && defined(CORE_MICRODUINO) +// Microduino Core RF + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 18; +uint8_t const SCL_PIN = 19; + +// SPI port +uint8_t const SS_PIN = 10; +uint8_t const MOSI_PIN = 11; +uint8_t const MISO_PIN = 12; +uint8_t const SCK_PIN = 13; + +static const pin_map_t digitalPinMap[] = { + {&DDRD, &PINE, &PORTE, 0}, // D0 PE0 + {&DDRD, &PINE, &PORTE, 1}, // D1 PE1 + {&DDRD, &PIND, &PORTD, 2}, // D2 PD2 + {&DDRD, &PIND, &PORTD, 3}, // D3 PD3 + {&DDRB, &PINE, &PORTE, 3}, // D4 PE3 + {&DDRB, &PINE, &PORTE, 4}, // D5 PE4 + {&DDRB, &PINE, &PORTE, 5}, // D6 PE5 + {&DDRB, &PINB, &PORTB, 7}, // D7 PB7 + {&DDRD, &PINB, &PORTB, 6}, // D8 PB6 + {&DDRD, &PINB, &PORTB, 5}, // D9 PB5 + {&DDRB, &PINB, &PORTB, 4}, // D10 PB4 + {&DDRB, &PINB, &PORTB, 2}, // D11 PB2 + {&DDRB, &PINB, &PORTB, 3}, // D12 PB3 + {&DDRB, &PINB, &PORTB, 1}, // D13 PB1 + {&DDRF, &PINF, &PORTF, 7}, // D14 PF7 + {&DDRF, &PINF, &PORTF, 6}, // D15 PF6 + {&DDRF, &PINF, &PORTF, 5}, // D16 PF5 + {&DDRF, &PINF, &PORTF, 4}, // D17 PF4 + {&DDRD, &PIND, &PORTD, 1}, // D18 PD1 + {&DDRD, &PIND, &PORTD, 0}, // D19 PD0 + {&DDRF, &PINF, &PORTF, 3}, // D20 PF3 + {&DDRF, &PINF, &PORTF, 2}, // D21 PF2 +}; +//------------------------------------------------------------------------------ +#elif defined(__AVR_ATmega32U4__) && defined(CORE_MICRODUINO) +// Microduino Core USB + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 18; +uint8_t const SCL_PIN = 19; + +// SPI port +uint8_t const SS_PIN = 10; +uint8_t const MOSI_PIN = 11; +uint8_t const MISO_PIN = 12; +uint8_t const SCK_PIN = 13; + +static const pin_map_t digitalPinMap[] = { + {&DDRD, &PIND, &PORTD, 2}, // D0 - PD2 + {&DDRD, &PIND, &PORTD, 3}, // D1 - PD3 + {&DDRE, &PINE, &PORTE, 6}, // D2 - PE6 + {&DDRD, &PIND, &PORTD, 6}, // D3 - PD6 + {&DDRD, &PIND, &PORTD, 7}, // D4 - PD7 + {&DDRC, &PINC, &PORTC, 6}, // D5 - PC6 + {&DDRC, &PINC, &PORTC, 7}, // D6 - PC7 + {&DDRE, &PINE, &PORTE, 7}, // D7 - PE7 + {&DDRB, &PINB, &PORTB, 6}, // D8 - PB6 + {&DDRB, &PINB, &PORTB, 5}, // D9 - PB5 + {&DDRB, &PINB, &PORTB, 0}, // D10 - PB0 + {&DDRB, &PINB, &PORTB, 2}, // D11 - MOSI - PB2 + {&DDRB, &PINB, &PORTB, 3}, // D12 -MISO - PB3 + {&DDRB, &PINB, &PORTB, 1}, // D13 -SCK - PB1 + {&DDRF, &PINF, &PORTF, 7}, // D14 - A0 - PF7 + {&DDRF, &PINF, &PORTF, 6}, // D15 - A1 - PF6 + {&DDRF, &PINF, &PORTF, 5}, // D16 - A2 - PF5 + {&DDRF, &PINF, &PORTF, 4}, // D17 - A3 - PF4 + {&DDRD, &PIND, &PORTD, 1}, // D18 - PD1 + {&DDRD, &PIND, &PORTD, 0}, // D19 - PD0 + {&DDRF, &PINF, &PORTF, 1}, // D20 - A6 - PF1 + {&DDRF, &PINF, &PORTF, 0}, // D21 - A7 - PF0 +}; +//------------------------------------------------------------------------------ +#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__) +// Sanguino + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 17; +uint8_t const SCL_PIN = 18; + +// SPI port +uint8_t const SS_PIN = 4; +uint8_t const MOSI_PIN = 5; +uint8_t const MISO_PIN = 6; +uint8_t const SCK_PIN = 7; + +static const pin_map_t digitalPinMap[] = { + {&DDRB, &PINB, &PORTB, 0}, // B0 0 + {&DDRB, &PINB, &PORTB, 1}, // B1 1 + {&DDRB, &PINB, &PORTB, 2}, // B2 2 + {&DDRB, &PINB, &PORTB, 3}, // B3 3 + {&DDRB, &PINB, &PORTB, 4}, // B4 4 + {&DDRB, &PINB, &PORTB, 5}, // B5 5 + {&DDRB, &PINB, &PORTB, 6}, // B6 6 + {&DDRB, &PINB, &PORTB, 7}, // B7 7 + {&DDRD, &PIND, &PORTD, 0}, // D0 8 + {&DDRD, &PIND, &PORTD, 1}, // D1 9 + {&DDRD, &PIND, &PORTD, 2}, // D2 10 + {&DDRD, &PIND, &PORTD, 3}, // D3 11 + {&DDRD, &PIND, &PORTD, 4}, // D4 12 + {&DDRD, &PIND, &PORTD, 5}, // D5 13 + {&DDRD, &PIND, &PORTD, 6}, // D6 14 + {&DDRD, &PIND, &PORTD, 7}, // D7 15 + {&DDRC, &PINC, &PORTC, 0}, // C0 16 + {&DDRC, &PINC, &PORTC, 1}, // C1 17 + {&DDRC, &PINC, &PORTC, 2}, // C2 18 + {&DDRC, &PINC, &PORTC, 3}, // C3 19 + {&DDRC, &PINC, &PORTC, 4}, // C4 20 + {&DDRC, &PINC, &PORTC, 5}, // C5 21 + {&DDRC, &PINC, &PORTC, 6}, // C6 22 + {&DDRC, &PINC, &PORTC, 7}, // C7 23 + {&DDRA, &PINA, &PORTA, 7}, // A7 24 + {&DDRA, &PINA, &PORTA, 6}, // A6 25 + {&DDRA, &PINA, &PORTA, 5}, // A5 26 + {&DDRA, &PINA, &PORTA, 4}, // A4 27 + {&DDRA, &PINA, &PORTA, 3}, // A3 28 + {&DDRA, &PINA, &PORTA, 2}, // A2 29 + {&DDRA, &PINA, &PORTA, 1}, // A1 30 + {&DDRA, &PINA, &PORTA, 0} // A0 31 +}; +//------------------------------------------------------------------------------ +#elif defined(__AVR_ATmega32U4__) +// Leonardo + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 2; +uint8_t const SCL_PIN = 3; + +// SPI port +uint8_t const SS_PIN = 17; +uint8_t const MOSI_PIN = 16; +uint8_t const MISO_PIN = 14; +uint8_t const SCK_PIN = 15; + +static const pin_map_t digitalPinMap[] = { + {&DDRD, &PIND, &PORTD, 2}, // D2 0 + {&DDRD, &PIND, &PORTD, 3}, // D3 1 + {&DDRD, &PIND, &PORTD, 1}, // D1 2 + {&DDRD, &PIND, &PORTD, 0}, // D0 3 + {&DDRD, &PIND, &PORTD, 4}, // D4 4 + {&DDRC, &PINC, &PORTC, 6}, // C6 5 + {&DDRD, &PIND, &PORTD, 7}, // D7 6 + {&DDRE, &PINE, &PORTE, 6}, // E6 7 + {&DDRB, &PINB, &PORTB, 4}, // B4 8 + {&DDRB, &PINB, &PORTB, 5}, // B5 9 + {&DDRB, &PINB, &PORTB, 6}, // B6 10 + {&DDRB, &PINB, &PORTB, 7}, // B7 11 + {&DDRD, &PIND, &PORTD, 6}, // D6 12 + {&DDRC, &PINC, &PORTC, 7}, // C7 13 + {&DDRB, &PINB, &PORTB, 3}, // B3 14 + {&DDRB, &PINB, &PORTB, 1}, // B1 15 + {&DDRB, &PINB, &PORTB, 2}, // B2 16 + {&DDRB, &PINB, &PORTB, 0}, // B0 17 + {&DDRF, &PINF, &PORTF, 7}, // F7 18 + {&DDRF, &PINF, &PORTF, 6}, // F6 19 + {&DDRF, &PINF, &PORTF, 5}, // F5 20 + {&DDRF, &PINF, &PORTF, 4}, // F4 21 + {&DDRF, &PINF, &PORTF, 1}, // F1 22 + {&DDRF, &PINF, &PORTF, 0}, // F0 23 +}; +//------------------------------------------------------------------------------ +#elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__) +// Teensy++ 1.0 & 2.0 + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 1; +uint8_t const SCL_PIN = 0; + +// SPI port +uint8_t const SS_PIN = 20; +uint8_t const MOSI_PIN = 22; +uint8_t const MISO_PIN = 23; +uint8_t const SCK_PIN = 21; + +static const pin_map_t digitalPinMap[] = { + {&DDRD, &PIND, &PORTD, 0}, // D0 0 + {&DDRD, &PIND, &PORTD, 1}, // D1 1 + {&DDRD, &PIND, &PORTD, 2}, // D2 2 + {&DDRD, &PIND, &PORTD, 3}, // D3 3 + {&DDRD, &PIND, &PORTD, 4}, // D4 4 + {&DDRD, &PIND, &PORTD, 5}, // D5 5 + {&DDRD, &PIND, &PORTD, 6}, // D6 6 + {&DDRD, &PIND, &PORTD, 7}, // D7 7 + {&DDRE, &PINE, &PORTE, 0}, // E0 8 + {&DDRE, &PINE, &PORTE, 1}, // E1 9 + {&DDRC, &PINC, &PORTC, 0}, // C0 10 + {&DDRC, &PINC, &PORTC, 1}, // C1 11 + {&DDRC, &PINC, &PORTC, 2}, // C2 12 + {&DDRC, &PINC, &PORTC, 3}, // C3 13 + {&DDRC, &PINC, &PORTC, 4}, // C4 14 + {&DDRC, &PINC, &PORTC, 5}, // C5 15 + {&DDRC, &PINC, &PORTC, 6}, // C6 16 + {&DDRC, &PINC, &PORTC, 7}, // C7 17 + {&DDRE, &PINE, &PORTE, 6}, // E6 18 + {&DDRE, &PINE, &PORTE, 7}, // E7 19 + {&DDRB, &PINB, &PORTB, 0}, // B0 20 + {&DDRB, &PINB, &PORTB, 1}, // B1 21 + {&DDRB, &PINB, &PORTB, 2}, // B2 22 + {&DDRB, &PINB, &PORTB, 3}, // B3 23 + {&DDRB, &PINB, &PORTB, 4}, // B4 24 + {&DDRB, &PINB, &PORTB, 5}, // B5 25 + {&DDRB, &PINB, &PORTB, 6}, // B6 26 + {&DDRB, &PINB, &PORTB, 7}, // B7 27 + {&DDRA, &PINA, &PORTA, 0}, // A0 28 + {&DDRA, &PINA, &PORTA, 1}, // A1 29 + {&DDRA, &PINA, &PORTA, 2}, // A2 30 + {&DDRA, &PINA, &PORTA, 3}, // A3 31 + {&DDRA, &PINA, &PORTA, 4}, // A4 32 + {&DDRA, &PINA, &PORTA, 5}, // A5 33 + {&DDRA, &PINA, &PORTA, 6}, // A6 34 + {&DDRA, &PINA, &PORTA, 7}, // A7 35 + {&DDRE, &PINE, &PORTE, 4}, // E4 36 + {&DDRE, &PINE, &PORTE, 5}, // E5 37 + {&DDRF, &PINF, &PORTF, 0}, // F0 38 + {&DDRF, &PINF, &PORTF, 1}, // F1 39 + {&DDRF, &PINF, &PORTF, 2}, // F2 40 + {&DDRF, &PINF, &PORTF, 3}, // F3 41 + {&DDRF, &PINF, &PORTF, 4}, // F4 42 + {&DDRF, &PINF, &PORTF, 5}, // F5 43 + {&DDRF, &PINF, &PORTF, 6}, // F6 44 + {&DDRF, &PINF, &PORTF, 7} // F7 45 +}; +//------------------------------------------------------------------------------ +#else // defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) +// 168 and 328 Arduinos + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 18; +uint8_t const SCL_PIN = 19; + +// SPI port +uint8_t const SS_PIN = 10; +uint8_t const MOSI_PIN = 11; +uint8_t const MISO_PIN = 12; +uint8_t const SCK_PIN = 13; + +static const pin_map_t digitalPinMap[] = { + {&DDRD, &PIND, &PORTD, 0}, // D0 0 + {&DDRD, &PIND, &PORTD, 1}, // D1 1 + {&DDRD, &PIND, &PORTD, 2}, // D2 2 + {&DDRD, &PIND, &PORTD, 3}, // D3 3 + {&DDRD, &PIND, &PORTD, 4}, // D4 4 + {&DDRD, &PIND, &PORTD, 5}, // D5 5 + {&DDRD, &PIND, &PORTD, 6}, // D6 6 + {&DDRD, &PIND, &PORTD, 7}, // D7 7 + {&DDRB, &PINB, &PORTB, 0}, // B0 8 + {&DDRB, &PINB, &PORTB, 1}, // B1 9 + {&DDRB, &PINB, &PORTB, 2}, // B2 10 + {&DDRB, &PINB, &PORTB, 3}, // B3 11 + {&DDRB, &PINB, &PORTB, 4}, // B4 12 + {&DDRB, &PINB, &PORTB, 5}, // B5 13 + {&DDRC, &PINC, &PORTC, 0}, // C0 14 + {&DDRC, &PINC, &PORTC, 1}, // C1 15 + {&DDRC, &PINC, &PORTC, 2}, // C2 16 + {&DDRC, &PINC, &PORTC, 3}, // C3 17 + {&DDRC, &PINC, &PORTC, 4}, // C4 18 + {&DDRC, &PINC, &PORTC, 5} // C5 19 +}; +#endif // defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) +//------------------------------------------------------------------------------ +static const uint8_t digitalPinCount = sizeof(digitalPinMap)/sizeof(pin_map_t); + +uint8_t badPinNumber(void) + __attribute__((error("Pin number is too large or not a constant"))); + +static inline __attribute__((always_inline)) + uint8_t getPinMode(uint8_t pin) { + if (__builtin_constant_p(pin) && pin < digitalPinCount) { + return (*digitalPinMap[pin].ddr >> digitalPinMap[pin].bit) & 1; + } else { + return badPinNumber(); + } +} +static inline __attribute__((always_inline)) + void setPinMode(uint8_t pin, uint8_t mode) { + if (__builtin_constant_p(pin) && pin < digitalPinCount) { + if (mode) { + *digitalPinMap[pin].ddr |= 1 << digitalPinMap[pin].bit; + } else { + *digitalPinMap[pin].ddr &= ~(1 << digitalPinMap[pin].bit); + } + } else { + badPinNumber(); + } +} +static inline __attribute__((always_inline)) + uint8_t fastDigitalRead(uint8_t pin) { + if (__builtin_constant_p(pin) && pin < digitalPinCount) { + return (*digitalPinMap[pin].pin >> digitalPinMap[pin].bit) & 1; + } else { + return badPinNumber(); + } +} +static inline __attribute__((always_inline)) + void fastDigitalWrite(uint8_t pin, uint8_t value) { + if (__builtin_constant_p(pin) && pin < digitalPinCount) { + if (value) { + *digitalPinMap[pin].port |= 1 << digitalPinMap[pin].bit; + } else { + *digitalPinMap[pin].port &= ~(1 << digitalPinMap[pin].bit); + } + } else { + badPinNumber(); + } +} +#endif // Sd2PinMap_h + +#elif defined (__CPU_ARC__) + +#if defined (__ARDUINO_ARC__) +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 18; +uint8_t const SCL_PIN = 19; + +// SPI port +uint8_t const SS_PIN = 10; +uint8_t const MOSI_PIN = 11; +uint8_t const MISO_PIN = 12; +uint8_t const SCK_PIN = 13; + +#endif // Arduino ARC + +#else +#error Architecture or board not supported. +#endif diff --git a/app/testdata/libraries/SD_1.2.1/SD/src/utility/SdFat.h b/app/testdata/libraries/SD_1.2.1/SD/src/utility/SdFat.h new file mode 100644 index 000000000..3ce3133c4 --- /dev/null +++ b/app/testdata/libraries/SD_1.2.1/SD/src/utility/SdFat.h @@ -0,0 +1,551 @@ +/* Arduino SdFat Library + * Copyright (C) 2009 by William Greiman + * + * This file is part of the Arduino SdFat 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 SdFat Library. If not, see + * . + */ +#ifndef SdFat_h +#define SdFat_h +/** + * \file + * SdFile and SdVolume classes + */ +#if defined (__AVR__) || defined (__CPU_ARC__) +#include +#endif +#include "Sd2Card.h" +#include "FatStructs.h" +#include "Print.h" +//------------------------------------------------------------------------------ +/** + * Allow use of deprecated functions if non-zero + */ +#define ALLOW_DEPRECATED_FUNCTIONS 1 +//------------------------------------------------------------------------------ +// forward declaration since SdVolume is used in SdFile +class SdVolume; +//============================================================================== +// SdFile class + +// 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; +/** ls() flag for recursive list of subdirectories */ +uint8_t const LS_R = 4; + +// use the gnu style oflag in open() +/** open() oflag for reading */ +uint8_t const O_READ = 0X01; +/** open() oflag - same as O_READ */ +uint8_t const O_RDONLY = O_READ; +/** open() oflag for write */ +uint8_t const O_WRITE = 0X02; +/** open() oflag - same as O_WRITE */ +uint8_t const O_WRONLY = O_WRITE; +/** open() oflag for reading and writing */ +uint8_t const O_RDWR = (O_READ | O_WRITE); +/** open() oflag 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; +// values for type_ +/** This SdFile has not been opened. */ +uint8_t const FAT_FILE_TYPE_CLOSED = 0; +/** SdFile for a file */ +uint8_t const FAT_FILE_TYPE_NORMAL = 1; +/** SdFile for a FAT16 root directory */ +uint8_t const FAT_FILE_TYPE_ROOT16 = 2; +/** SdFile for a FAT32 root directory */ +uint8_t const FAT_FILE_TYPE_ROOT32 = 3; +/** SdFile for a subdirectory */ +uint8_t const FAT_FILE_TYPE_SUBDIR = 4; +/** Test value for directory type */ +uint8_t const FAT_FILE_TYPE_MIN_DIR = FAT_FILE_TYPE_ROOT16; + +/** 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); +//------------------------------------------------------------------------------ +/** + * \class SdFile + * \brief Access FAT16 and FAT32 files on SD and SDHC cards. + */ +class SdFile : public Print { + public: + /** Create an instance of SdFile. */ + SdFile(void) : type_(FAT_FILE_TYPE_CLOSED) {} + /** + * writeError is set to true if an error occurs during a write(). + * Set writeError to false before calling print() and/or write() and check + * for true after calls to print() and/or write(). + */ + //bool writeError; + /** + * Cancel unbuffered reads for this file. + * See setUnbufferedRead() + */ + void clearUnbufferedRead(void) { + flags_ &= ~F_FILE_UNBUFFERED_READ; + } + uint8_t close(void); + uint8_t contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock); + uint8_t createContiguous(SdFile* dirFile, + const char* fileName, uint32_t size); + /** \return The current cluster number for a file or directory. */ + uint32_t curCluster(void) const {return curCluster_;} + /** \return The current position for a file or directory. */ + uint32_t curPosition(void) const {return curPosition_;} + /** + * Set the date/time callback function + * + * \param[in] dateTime The user's call back 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) { + // use explicit zero since NULL is not defined for Sanguino + dateTime_ = 0; + } + /** \return Address of the block that contains this file's directory. */ + uint32_t dirBlock(void) const {return dirBlock_;} + uint8_t dirEntry(dir_t* dir); + /** \return Index of this file's directory in the block dirBlock. */ + uint8_t dirIndex(void) const {return dirIndex_;} + static void dirName(const dir_t& dir, char* name); + /** \return The total number of bytes in a file or directory. */ + uint32_t fileSize(void) const {return fileSize_;} + /** \return The first cluster number for a file or directory. */ + uint32_t firstCluster(void) const {return firstCluster_;} + /** \return True if this is a SdFile for a directory else false. */ + uint8_t isDir(void) const {return type_ >= FAT_FILE_TYPE_MIN_DIR;} + /** \return True if this is a SdFile for a file else false. */ + uint8_t isFile(void) const {return type_ == FAT_FILE_TYPE_NORMAL;} + /** \return True if this is a SdFile for an open file/directory else false. */ + uint8_t isOpen(void) const {return type_ != FAT_FILE_TYPE_CLOSED;} + /** \return True if this is a SdFile for a subdirectory else false. */ + uint8_t isSubDir(void) const {return type_ == FAT_FILE_TYPE_SUBDIR;} + /** \return True if this is a SdFile for the root directory. */ + uint8_t isRoot(void) const { + return type_ == FAT_FILE_TYPE_ROOT16 || type_ == FAT_FILE_TYPE_ROOT32; + } + void ls(uint8_t flags = 0, uint8_t indent = 0); + uint8_t makeDir(SdFile* dir, const char* dirName); + uint8_t open(SdFile* dirFile, uint16_t index, uint8_t oflag); + uint8_t open(SdFile* dirFile, const char* fileName, uint8_t oflag); + + uint8_t openRoot(SdVolume* vol); + 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); + /** + * 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 read(void) { + uint8_t b; + return read(&b, 1) == 1 ? b : -1; + } + int16_t read(void* buf, uint16_t nbyte); + int8_t readDir(dir_t* dir); + static uint8_t remove(SdFile* dirFile, const char* fileName); + uint8_t remove(void); + /** Set the file's current position to zero. */ + void rewind(void) { + curPosition_ = curCluster_ = 0; + } + uint8_t rmDir(void); + uint8_t rmRfStar(void); + /** Set the files position to current position + \a pos. See seekSet(). */ + uint8_t seekCur(uint32_t pos) { + return seekSet(curPosition_ + pos); + } + /** + * Set the files current position to end of file. Useful to position + * a file for append. See seekSet(). + */ + uint8_t seekEnd(void) {return seekSet(fileSize_);} + uint8_t seekSet(uint32_t pos); + /** + * Use unbuffered reads to access this file. Used with Wave + * Shield ISR. Used with Sd2Card::partialBlockRead() in WaveRP. + * + * Not recommended for normal applications. + */ + void setUnbufferedRead(void) { + if (isFile()) flags_ |= F_FILE_UNBUFFERED_READ; + } + 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 sync(void); + /** Type of this SdFile. You should use isFile() or isDir() instead of type() + * if possible. + * + * \return The file or directory type. + */ + uint8_t type(void) const {return type_;} + uint8_t truncate(uint32_t size); + /** \return Unbuffered read flag. */ + uint8_t unbufferedRead(void) const { + return flags_ & F_FILE_UNBUFFERED_READ; + } + /** \return SdVolume that contains this file. */ + SdVolume* volume(void) const {return vol_;} + size_t write(uint8_t b); + size_t write(const void* buf, uint16_t nbyte); + size_t write(const char* str); +#ifdef __AVR__ + void write_P(PGM_P str); + void writeln_P(PGM_P str); +#endif +//------------------------------------------------------------------------------ +#if ALLOW_DEPRECATED_FUNCTIONS +// Deprecated functions - suppress cpplint warnings with NOLINT comment + /** \deprecated Use: + * uint8_t SdFile::contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock); + */ + uint8_t contiguousRange(uint32_t& bgnBlock, uint32_t& endBlock) { // NOLINT + return contiguousRange(&bgnBlock, &endBlock); + } + /** \deprecated Use: + * uint8_t SdFile::createContiguous(SdFile* dirFile, + * const char* fileName, uint32_t size) + */ + uint8_t createContiguous(SdFile& dirFile, // NOLINT + const char* fileName, uint32_t size) { + return createContiguous(&dirFile, fileName, size); + } + + /** + * \deprecated Use: + * static void SdFile::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 SdFile::dirEntry(dir_t* dir); */ + uint8_t dirEntry(dir_t& dir) {return dirEntry(&dir);} // NOLINT + /** \deprecated Use: + * uint8_t SdFile::makeDir(SdFile* dir, const char* dirName); + */ + uint8_t makeDir(SdFile& dir, const char* dirName) { // NOLINT + return makeDir(&dir, dirName); + } + /** \deprecated Use: + * uint8_t SdFile::open(SdFile* dirFile, const char* fileName, uint8_t oflag); + */ + uint8_t open(SdFile& dirFile, // NOLINT + const char* fileName, uint8_t oflag) { + return open(&dirFile, fileName, oflag); + } + /** \deprecated Do not use in new apps */ + uint8_t open(SdFile& dirFile, const char* fileName) { // NOLINT + return open(dirFile, fileName, O_RDWR); + } + /** \deprecated Use: + * uint8_t SdFile::open(SdFile* dirFile, uint16_t index, uint8_t oflag); + */ + uint8_t open(SdFile& dirFile, uint16_t index, uint8_t oflag) { // NOLINT + return open(&dirFile, index, oflag); + } + /** \deprecated Use: uint8_t SdFile::openRoot(SdVolume* vol); */ + uint8_t openRoot(SdVolume& vol) {return openRoot(&vol);} // NOLINT + + /** \deprecated Use: int8_t SdFile::readDir(dir_t* dir); */ + int8_t readDir(dir_t& dir) {return readDir(&dir);} // NOLINT + /** \deprecated Use: + * static uint8_t SdFile::remove(SdFile* dirFile, const char* fileName); + */ + static uint8_t remove(SdFile& dirFile, const char* fileName) { // NOLINT + return remove(&dirFile, fileName); + } +//------------------------------------------------------------------------------ +// rest are private + 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: + // bits defined in flags_ + // should be 0XF + static uint8_t const F_OFLAG = (O_ACCMODE | O_APPEND | O_SYNC); + // available bits + static uint8_t const F_UNUSED = 0X30; + // use unbuffered SD read + static uint8_t const F_FILE_UNBUFFERED_READ = 0X40; + // sync of directory entry required + static uint8_t const F_FILE_DIR_DIRTY = 0X80; + +// make sure F_OFLAG is ok +#if ((F_UNUSED | F_FILE_UNBUFFERED_READ | F_FILE_DIR_DIRTY) & F_OFLAG) +#error flags_ bits conflict +#endif // flags_ bits + + // private data + uint8_t flags_; // See above for definition of flags_ bits + uint8_t type_; // type of file see above for values + uint32_t curCluster_; // cluster for current file position + uint32_t curPosition_; // current file position in bytes from beginning + uint32_t dirBlock_; // SD block that contains directory entry for file + uint8_t dirIndex_; // index of entry in dirBlock 0 <= dirIndex_ <= 0XF + uint32_t fileSize_; // file size in bytes + uint32_t firstCluster_; // first cluster of file + SdVolume* vol_; // volume where file is located + + // private functions + uint8_t addCluster(void); + uint8_t addDirCluster(void); + dir_t* cacheDirEntry(uint8_t action); + static void (*dateTime_)(uint16_t* date, uint16_t* time); + static uint8_t make83Name(const char* str, uint8_t* name); + uint8_t openCachedEntry(uint8_t cacheIndex, uint8_t oflags); + dir_t* readDirCache(void); +}; +//============================================================================== +// SdVolume class +/** + * \brief Cache for an SD data block + */ +union cache_t { + /** Used to access cached file data blocks. */ + uint8_t data[512]; + /** Used to access cached FAT16 entries. */ + uint16_t fat16[256]; + /** Used to access cached FAT32 entries. */ + uint32_t fat32[128]; + /** Used to access cached directory entries. */ + dir_t dir[16]; + /** Used to access a cached MasterBoot Record. */ + mbr_t mbr; + /** Used to access to a cached FAT boot sector. */ + fbs_t fbs; +}; +//------------------------------------------------------------------------------ +/** + * \class SdVolume + * \brief Access FAT16 and FAT32 volumes on SD and SDHC cards. + */ +class SdVolume { + public: + /** Create an instance of SdVolume */ + SdVolume(void) :allocSearchStart_(2), fatType_(0) {} + /** Clear the cache and returns a pointer to the cache. Used by the WaveRP + * recorder to do raw write to the SD card. Not for normal apps. + */ + static uint8_t* cacheClear(void) { + cacheFlush(); + cacheBlockNumber_ = 0XFFFFFFFF; + return cacheBuffer_.data; + } + /** + * Initialize a FAT volume. Try partition one first then try super + * floppy format. + * + * \param[in] dev The Sd2Card 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 partition, not finding a valid + * FAT file system or an I/O error. + */ + uint8_t init(Sd2Card* dev) { return init(dev, 1) ? true : init(dev, 0);} + uint8_t init(Sd2Card* dev, uint8_t part); + + // inline functions that return volume info + /** \return The volume's cluster size in blocks. */ + uint8_t blocksPerCluster(void) const {return blocksPerCluster_;} + /** \return The number of blocks in one FAT. */ + uint32_t blocksPerFat(void) const {return blocksPerFat_;} + /** \return The total number of clusters in the volume. */ + uint32_t clusterCount(void) const {return clusterCount_;} + /** \return The shift count required to multiply by blocksPerCluster. */ + uint8_t clusterSizeShift(void) const {return clusterSizeShift_;} + /** \return The logical block number for the start of file data. */ + uint32_t dataStartBlock(void) const {return dataStartBlock_;} + /** \return The number of FAT structures on the volume. */ + uint8_t fatCount(void) const {return fatCount_;} + /** \return The logical block number for the start of the first FAT. */ + uint32_t fatStartBlock(void) const {return fatStartBlock_;} + /** \return The FAT type of the volume. Values are 12, 16 or 32. */ + uint8_t fatType(void) const {return fatType_;} + /** \return The number of entries in the root directory for FAT16 volumes. */ + uint32_t rootDirEntryCount(void) const {return rootDirEntryCount_;} + /** \return The logical block number for the start of the root directory + on FAT16 volumes or the first cluster number on FAT32 volumes. */ + uint32_t rootDirStart(void) const {return rootDirStart_;} + /** return a pointer to the Sd2Card object for this volume */ + static Sd2Card* sdCard(void) {return sdCard_;} +//------------------------------------------------------------------------------ +#if ALLOW_DEPRECATED_FUNCTIONS + // Deprecated functions - suppress cpplint warnings with NOLINT comment + /** \deprecated Use: uint8_t SdVolume::init(Sd2Card* dev); */ + uint8_t init(Sd2Card& dev) {return init(&dev);} // NOLINT + + /** \deprecated Use: uint8_t SdVolume::init(Sd2Card* dev, uint8_t vol); */ + uint8_t init(Sd2Card& dev, uint8_t part) { // NOLINT + return init(&dev, part); + } +#endif // ALLOW_DEPRECATED_FUNCTIONS +//------------------------------------------------------------------------------ + private: + // Allow SdFile access to SdVolume private data. + friend class SdFile; + + // value for action argument in cacheRawBlock to indicate read from cache + static uint8_t const CACHE_FOR_READ = 0; + // value for action argument in cacheRawBlock to indicate cache dirty + static uint8_t const CACHE_FOR_WRITE = 1; + + static cache_t cacheBuffer_; // 512 byte cache for device blocks + static uint32_t cacheBlockNumber_; // Logical number of block in the cache + static Sd2Card* sdCard_; // Sd2Card object for cache + static uint8_t cacheDirty_; // cacheFlush() will write block if true + static uint32_t cacheMirrorBlock_; // block number for mirror FAT +// + uint32_t allocSearchStart_; // start cluster for alloc search + uint8_t blocksPerCluster_; // cluster size in blocks + uint32_t blocksPerFat_; // FAT size in blocks + uint32_t clusterCount_; // clusters in one FAT + uint8_t clusterSizeShift_; // shift to convert cluster count to block count + uint32_t dataStartBlock_; // first data block number + uint8_t fatCount_; // number of FATs on volume + uint32_t fatStartBlock_; // start block for first FAT + uint8_t fatType_; // volume type (12, 16, OR 32) + uint16_t rootDirEntryCount_; // number of entries in FAT16 root dir + uint32_t rootDirStart_; // root start block for FAT16, cluster for FAT32 + //---------------------------------------------------------------------------- + uint8_t allocContiguous(uint32_t count, uint32_t* curCluster); + uint8_t blockOfCluster(uint32_t position) const { + return (position >> 9) & (blocksPerCluster_ - 1);} + uint32_t clusterStartBlock(uint32_t cluster) const { + return dataStartBlock_ + ((cluster - 2) << clusterSizeShift_);} + uint32_t blockNumber(uint32_t cluster, uint32_t position) const { + return clusterStartBlock(cluster) + blockOfCluster(position);} + static uint8_t cacheFlush(void); + static uint8_t cacheRawBlock(uint32_t blockNumber, uint8_t action); + static void cacheSetDirty(void) {cacheDirty_ |= CACHE_FOR_WRITE;} + static uint8_t cacheZeroBlock(uint32_t blockNumber); + uint8_t chainSize(uint32_t beginCluster, uint32_t* size) const; + uint8_t fatGet(uint32_t cluster, uint32_t* value) const; + uint8_t fatPut(uint32_t cluster, uint32_t value); + uint8_t fatPutEOC(uint32_t cluster) { + return fatPut(cluster, 0x0FFFFFFF); + } + uint8_t freeChain(uint32_t cluster); + uint8_t isEOC(uint32_t cluster) const { + return cluster >= (fatType_ == 16 ? FAT16EOC_MIN : FAT32EOC_MIN); + } + uint8_t readBlock(uint32_t block, uint8_t* dst) { + return sdCard_->readBlock(block, dst);} + uint8_t readData(uint32_t block, uint16_t offset, + uint16_t count, uint8_t* dst) { + return sdCard_->readData(block, offset, count, dst); + } + uint8_t writeBlock(uint32_t block, const uint8_t* dst) { + return sdCard_->writeBlock(block, dst); + } +}; +#endif // SdFat_h diff --git a/app/testdata/libraries/SD_1.2.1/SD/src/utility/SdFatUtil.h b/app/testdata/libraries/SD_1.2.1/SD/src/utility/SdFatUtil.h new file mode 100644 index 000000000..d1b4d538f --- /dev/null +++ b/app/testdata/libraries/SD_1.2.1/SD/src/utility/SdFatUtil.h @@ -0,0 +1,75 @@ +/* Arduino SdFat Library + * Copyright (C) 2008 by William Greiman + * + * This file is part of the Arduino SdFat 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 SdFat Library. If not, see + * . + */ +#ifndef SdFatUtil_h +#define SdFatUtil_h +/** + * \file + * Useful utility functions. + */ +#include +#ifdef __AVR__ +#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. */ +#endif +#define NOINLINE __attribute__((noinline,unused)) +#define UNUSEDOK __attribute__((unused)) +//------------------------------------------------------------------------------ +/** Return the number of bytes currently free in RAM. */ +static UNUSEDOK 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; +} +#ifdef __AVR__ +//------------------------------------------------------------------------------ +/** + * %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 // __AVR__ +#endif // #define SdFatUtil_h diff --git a/app/testdata/libraries/SD_1.2.1/SD/src/utility/SdFatmainpage.h b/app/testdata/libraries/SD_1.2.1/SD/src/utility/SdFatmainpage.h new file mode 100644 index 000000000..73b3b63bd --- /dev/null +++ b/app/testdata/libraries/SD_1.2.1/SD/src/utility/SdFatmainpage.h @@ -0,0 +1,202 @@ +/* Arduino SdFat Library + * Copyright (C) 2009 by William Greiman + * + * This file is part of the Arduino SdFat 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 SdFat Library. If not, see + * . + */ + +/** +\mainpage Arduino SdFat Library +
Copyright © 2009 by William Greiman +
+ +\section Intro Introduction +The Arduino SdFat Library is a minimal implementation of FAT16 and FAT32 +file systems on SD flash memory cards. Standard SD and high capacity +SDHC cards are supported. + +The SdFat only supports short 8.3 names. + +The main classes in SdFat are Sd2Card, SdVolume, and SdFile. + +The Sd2Card class supports access to standard SD cards and SDHC cards. Most +applications will only need to call the Sd2Card::init() member function. + +The SdVolume class supports FAT16 and FAT32 partitions. Most applications +will only need to call the SdVolume::init() member function. + +The SdFile class provides file access functions such as open(), read(), +remove(), write(), close() and sync(). This class supports access to the root +directory and subdirectories. + +A number of example are provided in the SdFat/examples folder. These were +developed to test SdFat and illustrate its use. + +SdFat was developed for high speed data recording. SdFat was used to implement +an audio record/play class, WaveRP, for the Adafruit Wave Shield. This +application uses special Sd2Card calls to write to contiguous files in raw mode. +These functions reduce write latency so that audio can be recorded with the +small amount of RAM in the Arduino. + +\section SDcard SD\SDHC 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. + +\section Hardware Hardware Configuration + +SdFat was developed using an + Adafruit Industries + Wave Shield. + +The hardware interface to the SD card should not use a resistor based level +shifter. SdFat 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(SPI_HALF_SPEED) to initialize the SD card. + +\section comment Bugs and Comments + +If you wish to report bugs or have comments, send email to fat16lib@sbcglobal.net. + +\section SdFatClass SdFat Usage + +SdFat 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. + +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. + +\note + The Arduino Print class uses character +at a time writes so it was necessary to use a \link SdFile::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 SdFile::write write() \endlink must call \link SdFile::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 SdFile::close() close() \endlink is called. + +\par +Applications must use care calling \link SdFile::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. + +It is possible to open a file with two or more instances of SdFile. A file may +be corrupted if data is written to the file by more than one instance of SdFile. + +\section HowTo How to format SD Cards as FAT Volumes + +You should use a freshly formatted SD card for best performance. FAT +file systems become slower if many files have been created and deleted. +This is because the directory entry for a deleted file is marked as deleted, +but is not deleted. When a new file is created, these entries must be scanned +before creating the file, a flaw in the FAT design. Also files can become +fragmented which causes reads and writes to be slower. + +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 format is to use SDFormatter +which can be downloaded from: + +http://www.sdcard.org/consumers/formatter/ + +SDFormatter aligns flash erase boundaries with file +system structures which reduces write latency and file system overhead. + +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. + +If you reformat the SD card 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 + +Adafruit Industries: + +http://www.adafruit.com/ + +http://www.ladyada.net/make/waveshield/ + +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 + + + */ diff --git a/app/testdata/libraries/SD_1.2.1/SD/src/utility/SdFile.cpp b/app/testdata/libraries/SD_1.2.1/SD/src/utility/SdFile.cpp new file mode 100644 index 000000000..620fc0d9b --- /dev/null +++ b/app/testdata/libraries/SD_1.2.1/SD/src/utility/SdFile.cpp @@ -0,0 +1,1263 @@ +/* Arduino SdFat Library + * Copyright (C) 2009 by William Greiman + * + * This file is part of the Arduino SdFat 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 SdFat Library. If not, see + * . + */ +#include "SdFat.h" +#ifdef __AVR__ +#include +#endif +#include +//------------------------------------------------------------------------------ +// callback function for date/time +void (*SdFile::dateTime_)(uint16_t* date, uint16_t* time) = NULL; + +#if ALLOW_DEPRECATED_FUNCTIONS +// suppress cpplint warnings with NOLINT comment +void (*SdFile::oldDateTime_)(uint16_t& date, uint16_t& time) = NULL; // NOLINT +#endif // ALLOW_DEPRECATED_FUNCTIONS +//------------------------------------------------------------------------------ +// add a cluster to a file +uint8_t SdFile::addCluster() { + if (!vol_->allocContiguous(1, &curCluster_)) return false; + + // if first cluster of file link to directory entry + if (firstCluster_ == 0) { + firstCluster_ = curCluster_; + flags_ |= F_FILE_DIR_DIRTY; + } + return true; +} +//------------------------------------------------------------------------------ +// Add a cluster to a directory file and zero the cluster. +// return with first block of cluster in the cache +uint8_t SdFile::addDirCluster(void) { + if (!addCluster()) return false; + + // zero data in cluster insure first cluster is in cache + uint32_t block = vol_->clusterStartBlock(curCluster_); + for (uint8_t i = vol_->blocksPerCluster_; i != 0; i--) { + if (!SdVolume::cacheZeroBlock(block + i - 1)) return false; + } + // Increase directory file size by cluster size + fileSize_ += 512UL << vol_->clusterSizeShift_; + return true; +} +//------------------------------------------------------------------------------ +// cache a file's directory entry +// return pointer to cached entry or null for failure +dir_t* SdFile::cacheDirEntry(uint8_t action) { + if (!SdVolume::cacheRawBlock(dirBlock_, action)) return NULL; + return SdVolume::cacheBuffer_.dir + dirIndex_; +} +//------------------------------------------------------------------------------ +/** + * 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 SdFile::close(void) { + if (!sync())return false; + type_ = FAT_FILE_TYPE_CLOSED; + return true; +} +//------------------------------------------------------------------------------ +/** + * Check for contiguous file and return its raw block range. + * + * \param[out] bgnBlock the first block address for the file. + * \param[out] endBlock the last block address 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 not contiguous, file has zero length + * or an I/O error occurred. + */ +uint8_t SdFile::contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock) { + // error if no blocks + if (firstCluster_ == 0) return false; + + for (uint32_t c = firstCluster_; ; c++) { + uint32_t next; + if (!vol_->fatGet(c, &next)) return false; + + // check for contiguous + if (next != (c + 1)) { + // error if not end of chain + if (!vol_->isEOC(next)) return false; + *bgnBlock = vol_->clusterStartBlock(firstCluster_); + *endBlock = vol_->clusterStartBlock(c) + + vol_->blocksPerCluster_ - 1; + return true; + } + } +} +//------------------------------------------------------------------------------ +/** + * Create and open a new contiguous file of a specified size. + * + * \note This function only supports short DOS 8.3 names. + * See open() for more information. + * + * \param[in] dirFile The directory where the file will be created. + * \param[in] fileName A valid DOS 8.3 file name. + * \param[in] size The desired file size. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + * Reasons for failure include \a fileName contains + * an invalid DOS 8.3 file name, the FAT volume has not been initialized, + * a file is already open, the file already exists, the root + * directory is full or an I/O error. + * + */ +uint8_t SdFile::createContiguous(SdFile* dirFile, + const char* fileName, uint32_t size) { + // don't allow zero length file + if (size == 0) return false; + if (!open(dirFile, fileName, O_CREAT | O_EXCL | O_RDWR)) return false; + + // calculate number of clusters needed + uint32_t count = ((size - 1) >> (vol_->clusterSizeShift_ + 9)) + 1; + + // allocate clusters + if (!vol_->allocContiguous(count, &firstCluster_)) { + remove(); + return false; + } + fileSize_ = size; + + // insure sync() will update dir entry + flags_ |= F_FILE_DIR_DIRTY; + return sync(); +} +//------------------------------------------------------------------------------ +/** + * 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 SdFile::dirEntry(dir_t* dir) { + // make sure fields on SD are correct + if (!sync()) return false; + + // read entry + dir_t* p = cacheDirEntry(SdVolume::CACHE_FOR_READ); + if (!p) return false; + + // copy to caller's struct + memcpy(dir, p, sizeof(dir_t)); + return true; +} +//------------------------------------------------------------------------------ +/** + * Format the name field of \a dir into the 13 byte array + * \a name in standard 8.3 short name format. + * + * \param[in] dir The directory structure containing the name. + * \param[out] name A 13 byte char array for the formatted name. + */ +void SdFile::dirName(const dir_t& dir, char* name) { + uint8_t j = 0; + for (uint8_t i = 0; i < 11; i++) { + if (dir.name[i] == ' ')continue; + if (i == 8) name[j++] = '.'; + name[j++] = dir.name[i]; + } + name[j] = 0; +} +//------------------------------------------------------------------------------ +/** List directory contents to Serial. + * + * \param[in] flags The inclusive OR of + * + * LS_DATE - %Print file modification date + * + * LS_SIZE - %Print file size. + * + * LS_R - Recursive list of subdirectories. + * + * \param[in] indent Amount of space before file name. Used for recursive + * list to indicate subdirectory level. + */ +void SdFile::ls(uint8_t flags, uint8_t indent) { + dir_t* p; + + rewind(); + while ((p = readDirCache())) { + // done if past last used entry + if (p->name[0] == DIR_NAME_FREE) break; + + // skip deleted entry and entries for . and .. + if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') continue; + + // only list subdirectories and files + if (!DIR_IS_FILE_OR_SUBDIR(p)) continue; + + // print any indent spaces + for (int8_t i = 0; i < indent; i++) Serial.print(' '); + + // print file name with possible blank fill + printDirName(*p, flags & (LS_DATE | LS_SIZE) ? 14 : 0); + + // print modify date/time if requested + if (flags & LS_DATE) { + printFatDate(p->lastWriteDate); + Serial.print(' '); + printFatTime(p->lastWriteTime); + } + // print size if requested + if (!DIR_IS_SUBDIR(p) && (flags & LS_SIZE)) { + Serial.print(' '); + Serial.print(p->fileSize); + } + Serial.println(); + + // list subdirectory content if requested + if ((flags & LS_R) && DIR_IS_SUBDIR(p)) { + uint16_t index = curPosition()/32 - 1; + SdFile s; + if (s.open(this, index, O_READ)) s.ls(flags, indent + 2); + seekSet(32 * (index + 1)); + } + } +} +//------------------------------------------------------------------------------ +// format directory name field from a 8.3 name string +uint8_t SdFile::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 + uint8_t b; +#if defined(__AVR__) + PGM_P p = PSTR("|<>^+=?/[];,*\"\\"); + while ((b = pgm_read_byte(p++))) if (b == c) return false; +#elif defined(__arm__) + const uint8_t valid[] = "|<>^+=?/[];,*\"\\"; + const uint8_t *p = valid; + while ((b = *p++)) if (b == c) return false; +#endif + // check size 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] != ' '; +} +//------------------------------------------------------------------------------ +/** Make a new directory. + * + * \param[in] dir An open SdFat instance for the directory that will containing + * the new directory. + * + * \param[in] dirName A valid 8.3 DOS name for the new directory. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + * Reasons for failure include this SdFile is already open, \a dir is not a + * directory, \a dirName is invalid or already exists in \a dir. + */ +uint8_t SdFile::makeDir(SdFile* dir, const char* dirName) { + dir_t d; + + // create a normal file + if (!open(dir, dirName, O_CREAT | O_EXCL | O_RDWR)) return false; + + // convert SdFile to directory + flags_ = O_READ; + type_ = FAT_FILE_TYPE_SUBDIR; + + // allocate and zero first cluster + if (!addDirCluster())return false; + + // force entry to SD + if (!sync()) return false; + + // cache entry - should already be in cache due to sync() call + dir_t* p = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); + if (!p) return false; + + // change directory entry attribute + p->attributes = DIR_ATT_DIRECTORY; + + // make entry for '.' + memcpy(&d, p, sizeof(d)); + for (uint8_t i = 1; i < 11; i++) d.name[i] = ' '; + d.name[0] = '.'; + + // cache block for '.' and '..' + uint32_t block = vol_->clusterStartBlock(firstCluster_); + if (!SdVolume::cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) return false; + + // copy '.' to block + memcpy(&SdVolume::cacheBuffer_.dir[0], &d, sizeof(d)); + + // make entry for '..' + d.name[1] = '.'; + if (dir->isRoot()) { + d.firstClusterLow = 0; + d.firstClusterHigh = 0; + } else { + d.firstClusterLow = dir->firstCluster_ & 0XFFFF; + d.firstClusterHigh = dir->firstCluster_ >> 16; + } + // copy '..' to block + memcpy(&SdVolume::cacheBuffer_.dir[1], &d, sizeof(d)); + + // set position after '..' + curPosition_ = 2 * sizeof(d); + + // write first block + return SdVolume::cacheFlush(); +} +//------------------------------------------------------------------------------ +/** + * Open a file or directory by name. + * + * \param[in] dirFile An open SdFat instance for the directory containing the + * file to be opened. + * + * \param[in] fileName A valid 8.3 DOS name for a file to be opened. + * + * \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 at 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. + * + * \note Directory files must be opened read only. Write and truncation is + * not allowed for directory files. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + * Reasons for failure include this SdFile is already open, \a difFile is not + * a directory, \a fileName is invalid, the file does not exist + * or can't be opened in the access mode specified by oflag. + */ +uint8_t SdFile::open(SdFile* dirFile, const char* fileName, uint8_t oflag) { + uint8_t dname[11]; + dir_t* p; + + // error if already open + if (isOpen())return false; + + if (!make83Name(fileName, dname)) return false; + vol_ = dirFile->vol_; + dirFile->rewind(); + + // bool for empty entry found + uint8_t emptyFound = false; + + // search for file + while (dirFile->curPosition_ < dirFile->fileSize_) { + uint8_t index = 0XF & (dirFile->curPosition_ >> 5); + p = dirFile->readDirCache(); + if (p == NULL) return false; + + if (p->name[0] == DIR_NAME_FREE || p->name[0] == DIR_NAME_DELETED) { + // remember first empty slot + if (!emptyFound) { + emptyFound = true; + dirIndex_ = index; + dirBlock_ = SdVolume::cacheBlockNumber_; + } + // 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 found file + return openCachedEntry(0XF & index, oflag); + } + } + // only create file if O_CREAT and O_WRITE + if ((oflag & (O_CREAT | O_WRITE)) != (O_CREAT | O_WRITE)) return false; + + // cache found slot or add cluster if end of file + if (emptyFound) { + p = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); + if (!p) return false; + } else { + if (dirFile->type_ == FAT_FILE_TYPE_ROOT16) return false; + + // add and zero cluster for dirFile - first cluster is in cache for write + if (!dirFile->addDirCluster()) return false; + + // use first entry in cluster + dirIndex_ = 0; + p = SdVolume::cacheBuffer_.dir; + } + // 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; + + // force write of entry to SD + if (!SdVolume::cacheFlush()) return false; + + // open entry in cache + return openCachedEntry(dirIndex_, oflag); +} +//------------------------------------------------------------------------------ +/** + * Open a file by index. + * + * \param[in] dirFile An open SdFat instance for the directory. + * + * \param[in] index The \a index of the directory entry for the file to be + * opened. The value for \a index is (directory file position)/32. + * + * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive + * OR of flags O_READ, O_WRITE, O_TRUNC, and O_SYNC. + * + * See open() by fileName for definition of flags and return values. + * + */ +uint8_t SdFile::open(SdFile* dirFile, uint16_t index, uint8_t oflag) { + // error if already open + if (isOpen())return false; + + // don't open existing file if O_CREAT and O_EXCL - user call error + if ((oflag & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL)) return false; + + vol_ = dirFile->vol_; + + // seek to location of entry + if (!dirFile->seekSet(32 * index)) return false; + + // read entry into cache + dir_t* p = dirFile->readDirCache(); + if (p == NULL) return false; + + // error if empty slot or '.' or '..' + if (p->name[0] == DIR_NAME_FREE || + p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') { + return false; + } + // open cached entry + return openCachedEntry(index & 0XF, oflag); +} +//------------------------------------------------------------------------------ +// open a cached directory entry. Assumes vol_ is initializes +uint8_t SdFile::openCachedEntry(uint8_t dirIndex, uint8_t oflag) { + // location of entry in cache + dir_t* p = SdVolume::cacheBuffer_.dir + dirIndex; + + // write or truncate is an error for a directory or read-only file + if (p->attributes & (DIR_ATT_READ_ONLY | DIR_ATT_DIRECTORY)) { + if (oflag & (O_WRITE | O_TRUNC)) return false; + } + // remember location of directory entry on SD + dirIndex_ = dirIndex; + dirBlock_ = SdVolume::cacheBlockNumber_; + + // copy first cluster number for directory fields + firstCluster_ = (uint32_t)p->firstClusterHigh << 16; + firstCluster_ |= p->firstClusterLow; + + // make sure it is a normal file or subdirectory + if (DIR_IS_FILE(p)) { + fileSize_ = p->fileSize; + type_ = FAT_FILE_TYPE_NORMAL; + } else if (DIR_IS_SUBDIR(p)) { + if (!vol_->chainSize(firstCluster_, &fileSize_)) return false; + type_ = FAT_FILE_TYPE_SUBDIR; + } else { + return false; + } + // save open flags for read/write + flags_ = oflag & (O_ACCMODE | O_SYNC | O_APPEND); + + // set to start of file + curCluster_ = 0; + curPosition_ = 0; + + // truncate file to zero length if requested + if (oflag & O_TRUNC) return truncate(0); + return true; +} +//------------------------------------------------------------------------------ +/** + * Open a volume's root directory. + * + * \param[in] vol The FAT volume containing the root directory to be opened. + * + * \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 + * or it a FAT12 volume. + */ +uint8_t SdFile::openRoot(SdVolume* vol) { + // error if file is already open + if (isOpen()) return false; + + if (vol->fatType() == 16) { + type_ = FAT_FILE_TYPE_ROOT16; + firstCluster_ = 0; + fileSize_ = 32 * vol->rootDirEntryCount(); + } else if (vol->fatType() == 32) { + type_ = FAT_FILE_TYPE_ROOT32; + firstCluster_ = vol->rootDirStart(); + if (!vol->chainSize(firstCluster_, &fileSize_)) return false; + } else { + // volume is not initialized or FAT12 + return false; + } + vol_ = vol; + // read only + flags_ = O_READ; + + // set to start of file + curCluster_ = 0; + curPosition_ = 0; + + // root has no directory entry + dirBlock_ = 0; + dirIndex_ = 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 SdFile::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.print('.'); + w++; + } + Serial.write(dir.name[i]); + w++; + } + if (DIR_IS_SUBDIR(&dir)) { + Serial.print('/'); + w++; + } + while (w < width) { + Serial.print(' '); + w++; + } +} +//------------------------------------------------------------------------------ +/** %Print a directory date field to Serial. + * + * Format is yyyy-mm-dd. + * + * \param[in] fatDate The date field from a directory entry. + */ +void SdFile::printFatDate(uint16_t fatDate) { + Serial.print(FAT_YEAR(fatDate)); + Serial.print('-'); + printTwoDigits(FAT_MONTH(fatDate)); + Serial.print('-'); + 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 SdFile::printFatTime(uint16_t fatTime) { + printTwoDigits(FAT_HOUR(fatTime)); + Serial.print(':'); + printTwoDigits(FAT_MINUTE(fatTime)); + Serial.print(':'); + printTwoDigits(FAT_SECOND(fatTime)); +} +//------------------------------------------------------------------------------ +/** %Print a value as two digits to Serial. + * + * \param[in] v Value to be printed, 0 <= \a v <= 99 + */ +void SdFile::printTwoDigits(uint8_t v) { + char str[3]; + str[0] = '0' + v/10; + str[1] = '0' + v % 10; + str[2] = 0; + Serial.print(str); +} +//------------------------------------------------------------------------------ +/** + * Read data from a file starting at the current 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, will 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, corrupt file system + * or an I/O error occurred. + */ +int16_t SdFile::read(void* buf, uint16_t nbyte) { + uint8_t* dst = reinterpret_cast(buf); + + // error if not open or write only + if (!isOpen() || !(flags_ & O_READ)) return -1; + + // max bytes left in file + if (nbyte > (fileSize_ - curPosition_)) nbyte = fileSize_ - curPosition_; + + // amount left to read + uint16_t toRead = nbyte; + while (toRead > 0) { + uint32_t block; // raw device block number + uint16_t offset = curPosition_ & 0X1FF; // offset in block + if (type_ == FAT_FILE_TYPE_ROOT16) { + block = vol_->rootDirStart() + (curPosition_ >> 9); + } else { + uint8_t blockOfCluster = vol_->blockOfCluster(curPosition_); + if (offset == 0 && blockOfCluster == 0) { + // start of new cluster + if (curPosition_ == 0) { + // use first cluster in file + curCluster_ = firstCluster_; + } else { + // get next cluster from FAT + if (!vol_->fatGet(curCluster_, &curCluster_)) return -1; + } + } + block = vol_->clusterStartBlock(curCluster_) + blockOfCluster; + } + uint16_t n = toRead; + + // amount to be read from current block + if (n > (512 - offset)) n = 512 - offset; + + // no buffering needed if n == 512 or user requests no buffering + if ((unbufferedRead() || n == 512) && + block != SdVolume::cacheBlockNumber_) { + if (!vol_->readData(block, offset, n, dst)) return -1; + dst += n; + } else { + // read block to cache and copy data to caller + if (!SdVolume::cacheRawBlock(block, SdVolume::CACHE_FOR_READ)) return -1; + uint8_t* src = SdVolume::cacheBuffer_.data + offset; + uint8_t* end = src + n; + while (src != end) *dst++ = *src++; + } + curPosition_ += n; + toRead -= n; + } + return nbyte; +} +//------------------------------------------------------------------------------ +/** + * Read the next directory entry from a directory file. + * + * \param[out] dir The dir_t struct that will receive the data. + * + * \return For success readDir() returns the number of bytes read. + * A value of zero will be returned if end of file is reached. + * If an error occurs, readDir() returns -1. Possible errors include + * readDir() called before a directory has been opened, this is not + * a directory file or an I/O error occurred. + */ +int8_t SdFile::readDir(dir_t* dir) { + int8_t n; + // if not a directory file or miss-positioned return an error + if (!isDir() || (0X1F & curPosition_)) return -1; + + while ((n = read(dir, sizeof(dir_t))) == sizeof(dir_t)) { + // last entry if DIR_NAME_FREE + if (dir->name[0] == DIR_NAME_FREE) break; + // skip empty entries and entry for . and .. + if (dir->name[0] == DIR_NAME_DELETED || dir->name[0] == '.') continue; + // return if normal file or subdirectory + if (DIR_IS_FILE_OR_SUBDIR(dir)) return n; + } + // error, end of file, or past last entry + return n < 0 ? -1 : 0; +} +//------------------------------------------------------------------------------ +// Read next directory entry into the cache +// Assumes file is correctly positioned +dir_t* SdFile::readDirCache(void) { + // error if not directory + if (!isDir()) return NULL; + + // index of entry in cache + uint8_t i = (curPosition_ >> 5) & 0XF; + + // use read to locate and cache block + if (read() < 0) return NULL; + + // advance to next entry + curPosition_ += 31; + + // return pointer to entry + return (SdVolume::cacheBuffer_.dir + i); +} +//------------------------------------------------------------------------------ +/** + * 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 read-only, is a directory, + * or an I/O error occurred. + */ +uint8_t SdFile::remove(void) { + // free any clusters - will fail if read-only or directory + if (!truncate(0)) return false; + + // cache directory entry + dir_t* d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); + if (!d) return false; + + // mark entry deleted + d->name[0] = DIR_NAME_DELETED; + + // set this SdFile closed + type_ = FAT_FILE_TYPE_CLOSED; + + // write entry to SD + return SdVolume::cacheFlush(); +} +//------------------------------------------------------------------------------ +/** + * Remove a file. + * + * The directory entry and all data for the file are deleted. + * + * \param[in] dirFile The directory that contains the file. + * \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 a directory, is read only, + * \a dirFile is not a directory, \a fileName is not found + * or an I/O error occurred. + */ +uint8_t SdFile::remove(SdFile* dirFile, const char* fileName) { + SdFile file; + if (!file.open(dirFile, fileName, O_WRITE)) return false; + return file.remove(); +} +//------------------------------------------------------------------------------ +/** Remove a directory file. + * + * The directory file will be removed only if it is empty and is not the + * root directory. rmDir() follows DOS and Windows and ignores the + * read-only attribute for the directory. + * + * \note This function should not be used to delete the 8.3 version of a + * directory that has a long name. For example if a directory has the + * long name "New folder" you should not delete the 8.3 name "NEWFOL~1". + * + * \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 a directory, is the root + * directory, is not empty, or an I/O error occurred. + */ +uint8_t SdFile::rmDir(void) { + // must be open subdirectory + if (!isSubDir()) return false; + + rewind(); + + // make sure directory is empty + while (curPosition_ < fileSize_) { + dir_t* p = readDirCache(); + if (p == NULL) return false; + // done if past last used entry + if (p->name[0] == DIR_NAME_FREE) break; + // skip empty slot or '.' or '..' + if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') continue; + // error not empty + if (DIR_IS_FILE_OR_SUBDIR(p)) return false; + } + // convert empty directory to normal file for remove + type_ = FAT_FILE_TYPE_NORMAL; + flags_ |= O_WRITE; + return remove(); +} +//------------------------------------------------------------------------------ +/** Recursively delete a directory and all contained files. + * + * This is like the Unix/Linux 'rm -rf *' if called with the root directory + * hence the name. + * + * Warning - This will remove all contents of the directory including + * subdirectories. The directory will then be removed if it is not root. + * The read-only attribute for files will be ignored. + * + * \note This function should not be used to delete the 8.3 version of + * a directory that has a long name. See remove() and rmDir(). + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +uint8_t SdFile::rmRfStar(void) { + rewind(); + while (curPosition_ < fileSize_) { + SdFile f; + + // remember position + uint16_t index = curPosition_/32; + + dir_t* p = readDirCache(); + if (!p) return false; + + // done if past last entry + if (p->name[0] == DIR_NAME_FREE) break; + + // skip empty slot or '.' or '..' + if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') continue; + + // skip if part of long file name or volume label in root + if (!DIR_IS_FILE_OR_SUBDIR(p)) continue; + + if (!f.open(this, index, O_READ)) return false; + if (f.isSubDir()) { + // recursively delete + if (!f.rmRfStar()) return false; + } else { + // ignore read-only + f.flags_ |= O_WRITE; + if (!f.remove()) return false; + } + // position to next entry if required + if (curPosition_ != (32u*(index + 1))) { + if (!seekSet(32u*(index + 1))) return false; + } + } + // don't try to delete root + if (isRoot()) return true; + return rmDir(); +} +//------------------------------------------------------------------------------ +/** + * Sets a file's 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 SdFile::seekSet(uint32_t pos) { + // error if file not open or seek past end of file + if (!isOpen() || pos > fileSize_) return false; + + if (type_ == FAT_FILE_TYPE_ROOT16) { + curPosition_ = pos; + return true; + } + if (pos == 0) { + // set position to start of file + curCluster_ = 0; + curPosition_ = 0; + return true; + } + // calculate cluster index for cur and new position + uint32_t nCur = (curPosition_ - 1) >> (vol_->clusterSizeShift_ + 9); + uint32_t nNew = (pos - 1) >> (vol_->clusterSizeShift_ + 9); + + if (nNew < nCur || curPosition_ == 0) { + // must follow chain from first cluster + curCluster_ = firstCluster_; + } else { + // advance from curPosition + nNew -= nCur; + } + while (nNew--) { + if (!vol_->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 SdFile::sync(void) { + // only allow open files and directories + if (!isOpen()) return false; + + if (flags_ & F_FILE_DIR_DIRTY) { + dir_t* d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); + if (!d) return false; + + // do not set filesize for dir files + if (!isDir()) d->fileSize = fileSize_; + + // update first cluster fields + d->firstClusterLow = firstCluster_ & 0XFFFF; + d->firstClusterHigh = firstCluster_ >> 16; + + // set modify time if user supplied a callback date/time function + if (dateTime_) { + dateTime_(&d->lastWriteDate, &d->lastWriteTime); + d->lastAccessDate = d->lastWriteDate; + } + // clear directory dirty + flags_ &= ~F_FILE_DIR_DIRTY; + } + return SdVolume::cacheFlush(); +} +//------------------------------------------------------------------------------ +/** + * Set 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. + * + * \note + * Modify and access timestamps may be overwritten if a date time callback + * function has been set by dateTimeCallback(). + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +uint8_t SdFile::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(SdVolume::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 states + d->creationTimeTenths = second & 1 ? 100 : 0; + } + if (flags & T_WRITE) { + d->lastWriteDate = dirDate; + d->lastWriteTime = dirTime; + } + SdVolume::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 SdFile::truncate(uint32_t length) { +// error if not a normal file or read-only + if (!isFile() || !(flags_ & O_WRITE)) return false; + + // error if length is greater than current size + if (length > fileSize_) return false; + + // fileSize and length are zero - nothing to do + if (fileSize_ == 0) return true; + + // remember position for seek after truncation + uint32_t newPos = curPosition_ > length ? length : curPosition_; + + // position to last cluster in truncated file + if (!seekSet(length)) return false; + + if (length == 0) { + // free all clusters + if (!vol_->freeChain(firstCluster_)) return false; + firstCluster_ = 0; + } else { + uint32_t toFree; + if (!vol_->fatGet(curCluster_, &toFree)) return false; + + if (!vol_->isEOC(toFree)) { + // free extra clusters + if (!vol_->freeChain(toFree)) return false; + + // current cluster is end of chain + if (!vol_->fatPutEOC(curCluster_)) return false; + } + } + fileSize_ = length; + + // need to update directory entry + flags_ |= F_FILE_DIR_DIRTY; + + if (!sync()) return false; + + // set file to correct position + return seekSet(newPos); +} +//------------------------------------------------------------------------------ +/** + * Write data to 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 0. Possible errors + * include write() is called before a file has been opened, write is called + * for a read-only file, device is full, a corrupt file system or an I/O error. + * + */ +size_t SdFile::write(const void* buf, uint16_t nbyte) { + // convert void* to uint8_t* - must be before goto statements + const uint8_t* src = reinterpret_cast(buf); + + // number of bytes left to write - must be before goto statements + uint16_t nToWrite = nbyte; + + // error if not a normal file or is read-only + if (!isFile() || !(flags_ & O_WRITE)) goto writeErrorReturn; + + // seek to end of file if append flag + if ((flags_ & O_APPEND) && curPosition_ != fileSize_) { + if (!seekEnd()) goto writeErrorReturn; + } + + while (nToWrite > 0) { + uint8_t blockOfCluster = vol_->blockOfCluster(curPosition_); + uint16_t blockOffset = curPosition_ & 0X1FF; + if (blockOfCluster == 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 { + uint32_t next; + if (!vol_->fatGet(curCluster_, &next)) return false; + if (vol_->isEOC(next)) { + // add cluster if at end of chain + if (!addCluster()) goto writeErrorReturn; + } else { + curCluster_ = next; + } + } + } + // max space in block + uint16_t n = 512 - blockOffset; + + // lesser of space and amount to write + if (n > nToWrite) n = nToWrite; + + // block for data write + uint32_t block = vol_->clusterStartBlock(curCluster_) + blockOfCluster; + if (n == 512) { + // full block - don't need to use cache + // invalidate cache if block is in cache + if (SdVolume::cacheBlockNumber_ == block) { + SdVolume::cacheBlockNumber_ = 0XFFFFFFFF; + } + if (!vol_->writeBlock(block, src)) goto writeErrorReturn; + src += 512; + } else { + if (blockOffset == 0 && curPosition_ >= fileSize_) { + // start of new block don't need to read into cache + if (!SdVolume::cacheFlush()) goto writeErrorReturn; + SdVolume::cacheBlockNumber_ = block; + SdVolume::cacheSetDirty(); + } else { + // rewrite part of block + if (!SdVolume::cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) { + goto writeErrorReturn; + } + } + uint8_t* dst = SdVolume::cacheBuffer_.data + blockOffset; + uint8_t* end = dst + n; + while (dst != end) *dst++ = *src++; + } + nToWrite -= n; + curPosition_ += 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: + // return for write error + //writeError = true; + setWriteError(); + return 0; +} +//------------------------------------------------------------------------------ +/** + * Write a byte to a file. Required by the Arduino Print class. + * + * Use SdFile::writeError to check for errors. + */ +size_t SdFile::write(uint8_t b) { + return write(&b, 1); +} +//------------------------------------------------------------------------------ +/** + * Write a string to a file. Used by the Arduino Print class. + * + * Use SdFile::writeError to check for errors. + */ +size_t SdFile::write(const char* str) { + return write(str, strlen(str)); +} +#ifdef __AVR__ +//------------------------------------------------------------------------------ +/** + * Write a PROGMEM string to a file. + * + * Use SdFile::writeError to check for errors. + */ +void SdFile::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 SdFile::writeError to check for errors. + */ +void SdFile::writeln_P(PGM_P str) { + write_P(str); + println(); +} +#endif diff --git a/app/testdata/libraries/SD_1.2.1/SD/src/utility/SdInfo.h b/app/testdata/libraries/SD_1.2.1/SD/src/utility/SdInfo.h new file mode 100644 index 000000000..acde74d97 --- /dev/null +++ b/app/testdata/libraries/SD_1.2.1/SD/src/utility/SdInfo.h @@ -0,0 +1,232 @@ +/* Arduino Sd2Card Library + * Copyright (C) 2009 by William Greiman + * + * This file is part of the Arduino Sd2Card 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 Sd2Card 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 +//------------------------------------------------------------------------------ +// SD card commands +/** GO_IDLE_STATE - init card in spi mode if CS low */ +uint8_t const CMD0 = 0X00; +/** SEND_IF_COND - verify SD Memory Card interface operating condition.*/ +uint8_t const CMD8 = 0X08; +/** SEND_CSD - read the Card Specific Data (CSD register) */ +uint8_t const CMD9 = 0X09; +/** SEND_CID - read the card identification information (CID register) */ +uint8_t const CMD10 = 0X0A; +/** SEND_STATUS - read the card status register */ +uint8_t const CMD13 = 0X0D; +/** READ_BLOCK - read a single data block from the card */ +uint8_t const CMD17 = 0X11; +/** WRITE_BLOCK - write a single data block to the card */ +uint8_t const CMD24 = 0X18; +/** WRITE_MULTIPLE_BLOCK - write blocks of data until a STOP_TRANSMISSION */ +uint8_t const CMD25 = 0X19; +/** ERASE_WR_BLK_START - sets the address of the first block to be erased */ +uint8_t const CMD32 = 0X20; +/** ERASE_WR_BLK_END - sets the address of the last block of the continuous + range to be erased*/ +uint8_t const CMD33 = 0X21; +/** ERASE - erase all previously selected blocks */ +uint8_t const CMD38 = 0X26; +/** APP_CMD - escape for application specific command */ +uint8_t const CMD55 = 0X37; +/** READ_OCR - read the OCR register of a card */ +uint8_t const CMD58 = 0X3A; +/** SET_WR_BLK_ERASE_COUNT - Set the number of write blocks to be + pre-erased before writing */ +uint8_t const ACMD23 = 0X17; +/** SD_SEND_OP_COMD - Sends host capacity support information and + activates the card's initialization process */ +uint8_t const ACMD41 = 0X29; +//------------------------------------------------------------------------------ +/** status for card in the ready state */ +uint8_t const R1_READY_STATE = 0X00; +/** status for card in the idle state */ +uint8_t const R1_IDLE_STATE = 0X01; +/** status bit for illegal command */ +uint8_t const R1_ILLEGAL_COMMAND = 0X04; +/** start data token for read or write single block*/ +uint8_t const DATA_START_BLOCK = 0XFE; +/** stop token for write multiple blocks*/ +uint8_t const STOP_TRAN_TOKEN = 0XFD; +/** start data token for write multiple blocks*/ +uint8_t const WRITE_MULTIPLE_TOKEN = 0XFC; +/** mask for data response tokens after a write block operation */ +uint8_t const DATA_RES_MASK = 0X1F; +/** write data accepted token */ +uint8_t const DATA_RES_ACCEPTED = 0X05; +//------------------------------------------------------------------------------ +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; +//------------------------------------------------------------------------------ +// CSD for version 1.00 cards +typedef struct CSDV1 { + // 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; +}csd1_t; +//------------------------------------------------------------------------------ +// CSD for version 2.00 cards +typedef struct CSDV2 { + // 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 reserved2 : 4; + unsigned dsr_imp : 1; + unsigned read_blk_misalign :1; + unsigned write_blk_misalign : 1; + unsigned read_bl_partial : 1; + // byte 7 + unsigned reserved3 : 2; + unsigned c_size_high : 6; + // byte 8 + uint8_t c_size_mid; + // byte 9 + uint8_t c_size_low; + // byte 10 + unsigned sector_size_high : 6; + unsigned erase_blk_en : 1; + unsigned reserved4 : 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 reserved5 : 2; + unsigned wp_grp_enable : 1; + // byte 13 + unsigned reserved6 : 5; + unsigned write_partial : 1; + unsigned write_bl_len_low : 2; + // byte 14 + unsigned reserved7: 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; +}csd2_t; +//------------------------------------------------------------------------------ +// union of old and new style CSD register +union csd_t { + csd1_t v1; + csd2_t v2; +}; +#endif // SdInfo_h diff --git a/app/testdata/libraries/SD_1.2.1/SD/src/utility/SdVolume.cpp b/app/testdata/libraries/SD_1.2.1/SD/src/utility/SdVolume.cpp new file mode 100644 index 000000000..2fbb8100b --- /dev/null +++ b/app/testdata/libraries/SD_1.2.1/SD/src/utility/SdVolume.cpp @@ -0,0 +1,295 @@ +/* Arduino SdFat Library + * Copyright (C) 2009 by William Greiman + * + * This file is part of the Arduino SdFat 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 SdFat Library. If not, see + * . + */ +#include "SdFat.h" +//------------------------------------------------------------------------------ +// raw block cache +// init cacheBlockNumber_to invalid SD block number +uint32_t SdVolume::cacheBlockNumber_ = 0XFFFFFFFF; +cache_t SdVolume::cacheBuffer_; // 512 byte cache for Sd2Card +Sd2Card* SdVolume::sdCard_; // pointer to SD card object +uint8_t SdVolume::cacheDirty_ = 0; // cacheFlush() will write block if true +uint32_t SdVolume::cacheMirrorBlock_ = 0; // mirror block for second FAT +//------------------------------------------------------------------------------ +// find a contiguous group of clusters +uint8_t SdVolume::allocContiguous(uint32_t count, uint32_t* curCluster) { + // start of group + uint32_t bgnCluster; + + // flag to save place to start next search + uint8_t setStart; + + // set search start cluster + if (*curCluster) { + // try to make file contiguous + bgnCluster = *curCluster + 1; + + // don't save new start location + setStart = false; + } else { + // start at likely place for free cluster + bgnCluster = allocSearchStart_; + + // save next search start if one cluster + setStart = 1 == count; + } + // end of group + uint32_t endCluster = bgnCluster; + + // last cluster of FAT + uint32_t fatEnd = clusterCount_ + 1; + + // search the FAT for free clusters + for (uint32_t n = 0;; n++, endCluster++) { + // can't find space checked all clusters + if (n >= clusterCount_) return false; + + // past end - start from beginning of FAT + if (endCluster > fatEnd) { + bgnCluster = endCluster = 2; + } + uint32_t f; + if (!fatGet(endCluster, &f)) return false; + + if (f != 0) { + // cluster in use try next cluster as bgnCluster + bgnCluster = endCluster + 1; + } else if ((endCluster - bgnCluster + 1) == count) { + // done - found space + break; + } + } + // mark end of chain + if (!fatPutEOC(endCluster)) return false; + + // link clusters + while (endCluster > bgnCluster) { + if (!fatPut(endCluster - 1, endCluster)) return false; + endCluster--; + } + if (*curCluster != 0) { + // connect chains + if (!fatPut(*curCluster, bgnCluster)) return false; + } + // return first cluster number to caller + *curCluster = bgnCluster; + + // remember possible next free cluster + if (setStart) allocSearchStart_ = bgnCluster + 1; + + return true; +} +//------------------------------------------------------------------------------ +uint8_t SdVolume::cacheFlush(void) { + if (cacheDirty_) { + if (!sdCard_->writeBlock(cacheBlockNumber_, cacheBuffer_.data)) { + return false; + } + // mirror FAT tables + if (cacheMirrorBlock_) { + if (!sdCard_->writeBlock(cacheMirrorBlock_, cacheBuffer_.data)) { + return false; + } + cacheMirrorBlock_ = 0; + } + cacheDirty_ = 0; + } + return true; +} +//------------------------------------------------------------------------------ +uint8_t SdVolume::cacheRawBlock(uint32_t blockNumber, uint8_t action) { + if (cacheBlockNumber_ != blockNumber) { + if (!cacheFlush()) return false; + if (!sdCard_->readBlock(blockNumber, cacheBuffer_.data)) return false; + cacheBlockNumber_ = blockNumber; + } + cacheDirty_ |= action; + return true; +} +//------------------------------------------------------------------------------ +// cache a zero block for blockNumber +uint8_t SdVolume::cacheZeroBlock(uint32_t blockNumber) { + if (!cacheFlush()) return false; + + // loop take less flash than memset(cacheBuffer_.data, 0, 512); + for (uint16_t i = 0; i < 512; i++) { + cacheBuffer_.data[i] = 0; + } + cacheBlockNumber_ = blockNumber; + cacheSetDirty(); + return true; +} +//------------------------------------------------------------------------------ +// return the size in bytes of a cluster chain +uint8_t SdVolume::chainSize(uint32_t cluster, uint32_t* size) const { + uint32_t s = 0; + do { + if (!fatGet(cluster, &cluster)) return false; + s += 512UL << clusterSizeShift_; + } while (!isEOC(cluster)); + *size = s; + return true; +} +//------------------------------------------------------------------------------ +// Fetch a FAT entry +uint8_t SdVolume::fatGet(uint32_t cluster, uint32_t* value) const { + if (cluster > (clusterCount_ + 1)) return false; + uint32_t lba = fatStartBlock_; + lba += fatType_ == 16 ? cluster >> 8 : cluster >> 7; + if (lba != cacheBlockNumber_) { + if (!cacheRawBlock(lba, CACHE_FOR_READ)) return false; + } + if (fatType_ == 16) { + *value = cacheBuffer_.fat16[cluster & 0XFF]; + } else { + *value = cacheBuffer_.fat32[cluster & 0X7F] & FAT32MASK; + } + return true; +} +//------------------------------------------------------------------------------ +// Store a FAT entry +uint8_t SdVolume::fatPut(uint32_t cluster, uint32_t value) { + // error if reserved cluster + if (cluster < 2) return false; + + // error if not in FAT + if (cluster > (clusterCount_ + 1)) return false; + + // calculate block address for entry + uint32_t lba = fatStartBlock_; + lba += fatType_ == 16 ? cluster >> 8 : cluster >> 7; + + if (lba != cacheBlockNumber_) { + if (!cacheRawBlock(lba, CACHE_FOR_READ)) return false; + } + // store entry + if (fatType_ == 16) { + cacheBuffer_.fat16[cluster & 0XFF] = value; + } else { + cacheBuffer_.fat32[cluster & 0X7F] = value; + } + cacheSetDirty(); + + // mirror second FAT + if (fatCount_ > 1) cacheMirrorBlock_ = lba + blocksPerFat_; + return true; +} +//------------------------------------------------------------------------------ +// free a cluster chain +uint8_t SdVolume::freeChain(uint32_t cluster) { + // clear free cluster location + allocSearchStart_ = 2; + + do { + uint32_t next; + if (!fatGet(cluster, &next)) return false; + + // free cluster + if (!fatPut(cluster, 0)) return false; + + cluster = next; + } while (!isEOC(cluster)); + + return true; +} +//------------------------------------------------------------------------------ +/** + * Initialize a FAT volume. + * + * \param[in] dev The SD card 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 partition, not finding a valid + * FAT file system in the specified partition or an I/O error. + */ +uint8_t SdVolume::init(Sd2Card* dev, uint8_t part) { + uint32_t volumeStartBlock = 0; + sdCard_ = dev; + // if part == 0 assume super floppy with FAT boot sector in block zero + // if part > 0 assume mbr volume with partition table + if (part) { + if (part > 4)return false; + if (!cacheRawBlock(volumeStartBlock, CACHE_FOR_READ)) return false; + part_t* p = &cacheBuffer_.mbr.part[part-1]; + if ((p->boot & 0X7F) !=0 || + p->totalSectors < 100 || + p->firstSector == 0) { + // not a valid partition + return false; + } + volumeStartBlock = p->firstSector; + } + if (!cacheRawBlock(volumeStartBlock, CACHE_FOR_READ)) return false; + bpb_t* bpb = &cacheBuffer_.fbs.bpb; + if (bpb->bytesPerSector != 512 || + bpb->fatCount == 0 || + bpb->reservedSectorCount == 0 || + bpb->sectorsPerCluster == 0) { + // not valid FAT volume + return false; + } + fatCount_ = bpb->fatCount; + blocksPerCluster_ = bpb->sectorsPerCluster; + + // determine shift that is same as multiply by blocksPerCluster_ + clusterSizeShift_ = 0; + while (blocksPerCluster_ != (1 << clusterSizeShift_)) { + // error if not power of 2 + if (clusterSizeShift_++ > 7) return false; + } + blocksPerFat_ = bpb->sectorsPerFat16 ? + bpb->sectorsPerFat16 : bpb->sectorsPerFat32; + + fatStartBlock_ = volumeStartBlock + bpb->reservedSectorCount; + + // count for FAT16 zero for FAT32 + rootDirEntryCount_ = bpb->rootDirEntryCount; + + // directory start for FAT16 dataStart for FAT32 + rootDirStart_ = fatStartBlock_ + bpb->fatCount * blocksPerFat_; + + // data start for FAT16 and FAT32 + dataStartBlock_ = rootDirStart_ + ((32 * bpb->rootDirEntryCount + 511)/512); + + // total blocks for FAT16 or FAT32 + uint32_t totalBlocks = bpb->totalSectors16 ? + bpb->totalSectors16 : bpb->totalSectors32; + // total data blocks + clusterCount_ = totalBlocks - (dataStartBlock_ - volumeStartBlock); + + // divide by cluster size to get cluster count + clusterCount_ >>= clusterSizeShift_; + + // FAT type is determined by cluster count + if (clusterCount_ < 4085) { + fatType_ = 12; + } else if (clusterCount_ < 65525) { + fatType_ = 16; + } else { + rootDirStart_ = bpb->fat32RootCluster; + fatType_ = 32; + } + return true; +} diff --git a/app/testdata/libraries/index_Bridge_only/library_index.json b/app/testdata/libraries/index_Bridge_only/library_index.json new file mode 100644 index 000000000..05426786d --- /dev/null +++ b/app/testdata/libraries/index_Bridge_only/library_index.json @@ -0,0 +1,284 @@ +{ + "libraries": [ + { + "name": "Bridge", + "version": "1.0.0", + "author": "Arduino", + "maintainer": "Arduino \u003cinfo@arduino.cc\u003e", + "sentence": "Enables the communication between the Linux processor and the AVR. For Arduino Yún and TRE only.", + "paragraph": "The Bridge library feature: access to the shared storage, run and manage linux processes, open a remote console, access to the linux file system, including the SD card, enstablish http clients or servers.", + "website": "http://arduino.cc/en/Reference/YunBridgeLibrary", + "category": "Communication", + "architectures": [ + "*" + ], + "types": [ + "Arduino" + ], + "url": "http://downloads.arduino.cc/libraries/github.com/arduino-libraries/Bridge-1.0.0.zip", + "archiveFileName": "Bridge-1.0.0.zip", + "size": 79554, + "checksum": "SHA-256:9b80eb3c4064a2905a2be385fc2ee0ab2d19f5add43a743776fa9bff30c662d7" + }, + { + "name": "Bridge", + "version": "1.0.1", + "author": "Arduino", + "maintainer": "Arduino \u003cinfo@arduino.cc\u003e", + "sentence": "Enables the communication between the Linux processor and the AVR. For Arduino Yún and TRE only.", + "paragraph": "The Bridge library feature: access to the shared storage, run and manage linux processes, open a remote console, access to the linux file system, including the SD card, enstablish http clients or servers.", + "website": "http://arduino.cc/en/Reference/YunBridgeLibrary", + "category": "Communication", + "architectures": [ + "*" + ], + "types": [ + "Arduino" + ], + "url": "http://downloads.arduino.cc/libraries/github.com/arduino-libraries/Bridge-1.0.1.zip", + "archiveFileName": "Bridge-1.0.1.zip", + "size": 79571, + "checksum": "SHA-256:72f177e2711d558f655937f9c85edff8fb83a738156ab3b2b4b765267f395af0" + }, + { + "name": "Bridge", + "version": "1.0.2", + "author": "Arduino", + "maintainer": "Arduino \u003cinfo@arduino.cc\u003e", + "sentence": "Enables the communication between the Linux processor and the AVR. For Arduino Yún and TRE only.", + "paragraph": "The Bridge library feature: access to the shared storage, run and manage linux processes, open a remote console, access to the linux file system, including the SD card, enstablish http clients or servers.", + "website": "http://arduino.cc/en/Reference/YunBridgeLibrary", + "category": "Communication", + "architectures": [ + "*" + ], + "types": [ + "Arduino" + ], + "url": "http://downloads.arduino.cc/libraries/github.com/arduino-libraries/Bridge-1.0.2.zip", + "archiveFileName": "Bridge-1.0.2.zip", + "size": 79574, + "checksum": "SHA-256:8b228c5d2025682ef4bdefbee7682ef31025c1c061156757d20b247ac4cc8344" + }, + { + "name": "Bridge", + "version": "1.0.3", + "author": "Arduino", + "maintainer": "Arduino \u003cinfo@arduino.cc\u003e", + "sentence": "Enables the communication between the Linux processor and the AVR. For Arduino Yún and TRE only.", + "paragraph": "The Bridge library feature: access to the shared storage, run and manage linux processes, open a remote console, access to the linux file system, including the SD card, enstablish http clients or servers.", + "website": "http://arduino.cc/en/Reference/YunBridgeLibrary", + "category": "Communication", + "architectures": [ + "*" + ], + "types": [ + "Arduino" + ], + "url": "http://downloads.arduino.cc/libraries/github.com/arduino-libraries/Bridge-1.0.3.zip", + "archiveFileName": "Bridge-1.0.3.zip", + "size": 79616, + "checksum": "SHA-256:ead0482c236be1b9467cbb68481f9a0e6dcd30066bb069569ed0804b19a6a832" + }, + { + "name": "Bridge", + "version": "1.0.4", + "author": "Arduino", + "maintainer": "Arduino \u003cinfo@arduino.cc\u003e", + "sentence": "Enables the communication between the Linux processor and the AVR. For Arduino Yún and TRE only.", + "paragraph": "The Bridge library feature: access to the shared storage, run and manage linux processes, open a remote console, access to the linux file system, including the SD card, enstablish http clients or servers.", + "website": "http://arduino.cc/en/Reference/YunBridgeLibrary", + "category": "Communication", + "architectures": [ + "*" + ], + "types": [ + "Arduino" + ], + "url": "http://downloads.arduino.cc/libraries/github.com/arduino-libraries/Bridge-1.0.4.zip", + "archiveFileName": "Bridge-1.0.4.zip", + "size": 79635, + "checksum": "SHA-256:cb093c35c572f2a63f1dbe52a2bf3f4234aa3f0327b6bc32ebce023c9819d313" + }, + { + "name": "Bridge", + "version": "1.0.5", + "author": "Arduino", + "maintainer": "Arduino \u003cinfo@arduino.cc\u003e", + "sentence": "Enables the communication between the Linux processor and the AVR. For Arduino Yún and TRE only.", + "paragraph": "The Bridge library feature: access to the shared storage, run and manage linux processes, open a remote console, access to the linux file system, including the SD card, enstablish http clients or servers.", + "website": "http://www.arduino.cc/en/Reference/YunBridgeLibrary", + "category": "Communication", + "architectures": [ + "*" + ], + "types": [ + "Arduino" + ], + "url": "http://downloads.arduino.cc/libraries/github.com/arduino-libraries/Bridge-1.0.5.zip", + "archiveFileName": "Bridge-1.0.5.zip", + "size": 79691, + "checksum": "SHA-256:4541c53e88fb4d829d93a7ff5293b8d4bcc731cbfd89243e1f4d3361712b5257" + }, + { + "name": "Bridge", + "version": "1.0.6", + "author": "Arduino", + "maintainer": "Arduino \u003cinfo@arduino.cc\u003e", + "sentence": "Enables the communication between the Linux processor and the AVR. For Arduino Yún and TRE only.", + "paragraph": "The Bridge library feature: access to the shared storage, run and manage linux processes, open a remote console, access to the linux file system, including the SD card, enstablish http clients or servers.", + "website": "http://www.arduino.cc/en/Reference/YunBridgeLibrary", + "category": "Communication", + "architectures": [ + "*" + ], + "types": [ + "Arduino" + ], + "url": "http://downloads.arduino.cc/libraries/github.com/arduino-libraries/Bridge-1.0.6.zip", + "archiveFileName": "Bridge-1.0.6.zip", + "size": 79699, + "checksum": "SHA-256:4722f3d6cea9bcea355078ca531a295c53a867f58a9de9b907984fcb38d7826d" + }, + { + "name": "Bridge", + "version": "1.0.7", + "author": "Arduino", + "maintainer": "Arduino \u003cinfo@arduino.cc\u003e", + "sentence": "Enables the communication between the Linux processor and the AVR. For Arduino Yún and TRE only.", + "paragraph": "The Bridge library feature: access to the shared storage, run and manage linux processes, open a remote console, access to the linux file system, including the SD card, enstablish http clients or servers.", + "website": "http://www.arduino.cc/en/Reference/YunBridgeLibrary", + "category": "Communication", + "architectures": [ + "*" + ], + "types": [ + "Arduino" + ], + "url": "http://downloads.arduino.cc/libraries/github.com/arduino-libraries/Bridge-1.0.7.zip", + "archiveFileName": "Bridge-1.0.7.zip", + "size": 80447, + "checksum": "SHA-256:48e0e63cb5f49e9ecf318441b6bf22aebee3fec87e88877902cddd93ad30721d" + }, + { + "name": "Bridge", + "version": "1.1.0", + "author": "Arduino", + "maintainer": "Arduino \u003cinfo@arduino.cc\u003e", + "sentence": "Enables the communication between the Linux processor and the AVR. For Arduino Yún and TRE only.", + "paragraph": "The Bridge library feature: access to the shared storage, run and manage linux processes, open a remote console, access to the linux file system, including the SD card, enstablish http clients or servers.", + "website": "http://www.arduino.cc/en/Reference/YunBridgeLibrary", + "category": "Communication", + "architectures": [ + "*" + ], + "types": [ + "Arduino" + ], + "url": "http://downloads.arduino.cc/libraries/github.com/arduino-libraries/Bridge-1.1.0.zip", + "archiveFileName": "Bridge-1.1.0.zip", + "size": 58761, + "checksum": "SHA-256:6d12dc0e0e0a7f28a2d70f4ed662c6084b2bbd3ae0a3830e6a6f0b3bc5e25308" + }, + { + "name": "Bridge", + "version": "1.6.0", + "author": "Arduino", + "maintainer": "Arduino \u003cinfo@arduino.cc\u003e", + "sentence": "Enables the communication between the Linux processor and the AVR. For Arduino Yún and TRE only.", + "paragraph": "The Bridge library feature: access to the shared storage, run and manage linux processes, open a remote console, access to the linux file system, including the SD card, enstablish http clients or servers.", + "website": "http://www.arduino.cc/en/Reference/YunBridgeLibrary", + "category": "Communication", + "architectures": [ + "*" + ], + "types": [ + "Arduino" + ], + "url": "http://downloads.arduino.cc/libraries/github.com/arduino-libraries/Bridge-1.6.0.zip", + "archiveFileName": "Bridge-1.6.0.zip", + "size": 59403, + "checksum": "SHA-256:a8cf61d099550cd9a6f37f1f1a40369a6448cc52c2a87183e27240915b858fd7" + }, + { + "name": "Bridge", + "version": "1.6.1", + "author": "Arduino", + "maintainer": "Arduino \u003cinfo@arduino.cc\u003e", + "sentence": "Enables the communication between the Linux processor and the microcontroller. For Arduino/Genuino Yún, Yún Shield and TRE only.", + "paragraph": "The Bridge library feature: access to the shared storage, run and manage linux processes, open a remote console, access to the linux file system, including the SD card, enstablish http clients or servers.", + "website": "http://www.arduino.cc/en/Reference/YunBridgeLibrary", + "category": "Communication", + "architectures": [ + "*" + ], + "types": [ + "Arduino" + ], + "url": "http://downloads.arduino.cc/libraries/github.com/arduino-libraries/Bridge-1.6.1.zip", + "archiveFileName": "Bridge-1.6.1.zip", + "size": 61137, + "checksum": "SHA-256:f0b33f6191a9b8bb3d693bd3f811ef175b92470a420d6112bbabdfd41c9efc62" + }, + { + "name": "Bridge", + "version": "1.6.2", + "author": "Arduino", + "maintainer": "Arduino \u003cinfo@arduino.cc\u003e", + "sentence": "Enables the communication between the Linux processor and the microcontroller. For Arduino/Genuino Yún, Yún Shield and TRE only.", + "paragraph": "The Bridge library feature: access to the shared storage, run and manage linux processes, open a remote console, access to the linux file system, including the SD card, enstablish http clients or servers.", + "website": "http://www.arduino.cc/en/Reference/YunBridgeLibrary", + "category": "Communication", + "architectures": [ + "*" + ], + "types": [ + "Arduino" + ], + "url": "http://downloads.arduino.cc/libraries/github.com/arduino-libraries/Bridge-1.6.2.zip", + "archiveFileName": "Bridge-1.6.2.zip", + "size": 66457, + "checksum": "SHA-256:d6ac5785fd1dad7d34c31e02c76e4cbc08b8a20906fc4e40a48cd2569a2fcdd8" + }, + { + "name": "Bridge", + "version": "1.6.3", + "author": "Arduino", + "maintainer": "Arduino \u003cinfo@arduino.cc\u003e", + "sentence": "Enables the communication between the Linux processor and the microcontroller. For Arduino/Genuino Yún, Yún Shield and TRE only.", + "paragraph": "The Bridge library feature: access to the shared storage, run and manage linux processes, open a remote console, access to the linux file system, including the SD card, enstablish http clients or servers.", + "website": "http://www.arduino.cc/en/Reference/YunBridgeLibrary", + "category": "Communication", + "architectures": [ + "*" + ], + "types": [ + "Arduino" + ], + "url": "http://downloads.arduino.cc/libraries/github.com/arduino-libraries/Bridge-1.6.3.zip", + "archiveFileName": "Bridge-1.6.3.zip", + "size": 61306, + "checksum": "SHA-256:a2f81451f2379a633ffff96a89321c519bea9cd33d986ece9f1d3c95a0d49b32" + }, + { + "name": "Bridge", + "version": "1.7.0", + "author": "Arduino", + "maintainer": "Arduino \u003cinfo@arduino.cc\u003e", + "sentence": "Enables the communication between the Linux processor and the microcontroller. For Arduino/Genuino Yún, Yún Shield and TRE only.", + "paragraph": "The Bridge library feature: access to the shared storage, run and manage linux processes, open a remote console, access to the linux file system, including the SD card, enstablish http clients or servers.", + "website": "http://www.arduino.cc/en/Reference/YunBridgeLibrary", + "category": "Communication", + "architectures": [ + "*" + ], + "types": [ + "Arduino" + ], + "url": "http://downloads.arduino.cc/libraries/github.com/arduino-libraries/Bridge-1.7.0.zip", + "archiveFileName": "Bridge-1.7.0.zip", + "size": 61431, + "checksum": "SHA-256:3bb1bae4ca76ac8849977fe9c5966a1d18d97bdfd3d808ee2a66581576acfa58" + } + ] +} \ No newline at end of file diff --git a/app/testdata/libraries/index_SD_only/library_index.json b/app/testdata/libraries/index_SD_only/library_index.json new file mode 100644 index 000000000..309cc1037 --- /dev/null +++ b/app/testdata/libraries/index_SD_only/library_index.json @@ -0,0 +1,70 @@ +{ + "libraries": [ + { + "name": "SD", + "version": "1.1.1", + "author": "Arduino, SparkFun", + "maintainer": "Arduino \u003cinfo@arduino.cc\u003e", + "sentence": "Enables reading and writing on SD cards.", + "paragraph": "Once an SD memory card is connected to the SPI interface of the Arduino or Genuino board you can create files and read/write on them. You can also move through directories on the SD card.", + "website": "http://www.arduino.cc/en/Reference/SD", + "category": "Data Storage", + "architectures": [ + "*" + ], + "types": [ + "Arduino" + ], + "url": "http://downloads.arduino.cc/libraries/github.com/arduino-libraries/SD-1.1.1.zip", + "archiveFileName": "SD-1.1.1.zip", + "size": 59689, + "checksum": "SHA-256:231414a512e385ffd2c47d5bec547f8e3b7a3ace340769c7ff745e99d43f68fa" + }, + { + "name": "SD", + "version": "1.2.0", + "author": "Arduino, SparkFun", + "maintainer": "Arduino \u003cinfo@arduino.cc\u003e", + "sentence": "Enables reading and writing on SD cards.", + "paragraph": "Once an SD memory card is connected to the SPI interface of the Arduino or Genuino board you can create files and read/write on them. You can also move through directories on the SD card.", + "website": "http://www.arduino.cc/en/Reference/SD", + "category": "Data Storage", + "architectures": [ + "avr", + "sam", + "samd", + "arc32" + ], + "types": [ + "Arduino" + ], + "url": "http://downloads.arduino.cc/libraries/github.com/arduino-libraries/SD-1.2.0.zip", + "archiveFileName": "SD-1.2.0.zip", + "size": 59845, + "checksum": "SHA-256:9b43fc21676172ea8323a97497deb4502e506767935304145a97f8b261e75d64" + }, + { + "name": "SD", + "version": "1.2.1", + "author": "Arduino, SparkFun", + "maintainer": "Arduino \u003cinfo@arduino.cc\u003e", + "sentence": "Enables reading and writing on SD cards.", + "paragraph": "Once an SD memory card is connected to the SPI interface of the Arduino or Genuino board you can create files and read/write on them. You can also move through directories on the SD card.", + "website": "http://www.arduino.cc/en/Reference/SD", + "category": "Data Storage", + "architectures": [ + "avr", + "sam", + "samd", + "arc32" + ], + "types": [ + "Arduino" + ], + "url": "http://downloads.arduino.cc/libraries/github.com/arduino-libraries/SD-1.2.1.zip", + "archiveFileName": "SD-1.2.1.zip", + "size": 59849, + "checksum": "SHA-256:933a62abbe7bc18f736e26a33a63c70e76f971c7bd6954f745877c6a887d0b0e" + } + ] +}