libraries / Bridge / examples / FileWriteScript / FileWriteScript.inoon commit Added final version of code (649c546)
   1/*
   2  Write to file using FileIO classes.
   3
   4 This sketch demonstrate how to write file into the Yún filesystem.
   5 A shell script file is created in /tmp, and it is executed afterwards.
   6
   7 created 7 June 2010
   8 by Cristian Maglie
   9
  10 This example code is in the public domain.
  11
  12 http://www.arduino.cc/en/Tutorial/FileWriteScript
  13
  14 */
  15
  16#include <FileIO.h>
  17
  18void setup() {
  19  // Setup Bridge (needed every time we communicate with the Arduino Yún)
  20  Bridge.begin();
  21  // Initialize the Serial
  22  SerialUSB.begin(9600);
  23
  24  while (!SerialUSB); // wait for Serial port to connect.
  25  SerialUSB.println("File Write Script example\n\n");
  26
  27  // Setup File IO
  28  FileSystem.begin();
  29
  30  // Upload script used to gain network statistics
  31  uploadScript();
  32}
  33
  34void loop() {
  35  // Run stats script every 5 secs.
  36  runScript();
  37  delay(5000);
  38}
  39
  40// this function creates a file into the linux processor that contains a shell script
  41// to check the network traffic of the WiFi interface
  42void uploadScript() {
  43  // Write our shell script in /tmp
  44  // Using /tmp stores the script in RAM this way we can preserve
  45  // the limited amount of FLASH erase/write cycles
  46  File script = FileSystem.open("/tmp/wlan-stats.sh", FILE_WRITE);
  47  // Shell script header
  48  script.print("#!/bin/sh\n");
  49  // shell commands:
  50  // ifconfig: is a command line utility for controlling the network interfaces.
  51  //           wlan0 is the interface we want to query
  52  // grep: search inside the output of the ifconfig command the "RX bytes" keyword
  53  //       and extract the line that contains it
  54  script.print("ifconfig wlan0 | grep 'RX bytes'\n");
  55  script.close();  // close the file
  56
  57  // Make the script executable
  58  Process chmod;
  59  chmod.begin("chmod");      // chmod: change mode
  60  chmod.addParameter("+x");  // x stays for executable
  61  chmod.addParameter("/tmp/wlan-stats.sh");  // path to the file to make it executable
  62  chmod.run();
  63}
  64
  65
  66// this function run the script and read the output data
  67void runScript() {
  68  // Run the script and show results on the Serial
  69  Process myscript;
  70  myscript.begin("/tmp/wlan-stats.sh");
  71  myscript.run();
  72
  73  String output = "";
  74
  75  // read the output of the script
  76  while (myscript.available()) {
  77    output += (char)myscript.read();
  78  }
  79  // remove the blank spaces at the beginning and the ending of the string
  80  output.trim();
  81  SerialUSB.println(output);
  82  SerialUSB.flush();
  83}
  84