aboutsummaryrefslogtreecommitdiff
path: root/libraries/Bridge/examples/FileWriteScript/FileWriteScript.ino
blob: d5bbb2688701c519cbc86d772ea4bff2418aae1d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
  Write to file using FileIO classes.
 
 This sketch demonstrate how to write file into the Yún filesystem.
 A shell script file is created in /tmp, and it is executed afterwards.
 
 */
 
#include <FileIO.h>

void setup() {
  // Setup Bridge (needed every time we communicate with the Arduino Yún)
  Bridge.begin();

  // Setup Console
  Console.begin();
  // Buffering improves Console performance, but we must remember to
  // finish sending using the Console.flush() command.
  Console.buffer(64);
  
  // Setup File IO
  SD.begin();

  // Upload script used to gain network statistics  
  uploadScript();
}  

void loop() {
  // Run stats script every 5 secs.
  runScript();
  delay(5000);
}

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 = SD.open("/tmp/wlan-stats.sh", FILE_WRITE);
  script.print("#!/bin/sh\n");
  script.print("ifconfig wlan0 | grep \"RX bytes\" | tr ':' ' ' | awk \"{ print \\$3 \\\" \\\" \\$8 }\"\n");
  script.close();
  
  // Make the script executable
  Process chmod;
  chmod.begin("chmod");
  chmod.addParameter("+x");
  chmod.addParameter("/tmp/wlan-stats.sh");
  chmod.run();
}

void runScript() {
  // Launch script and show results on the console
  Process myscript;
  myscript.begin("/tmp/wlan-stats.sh");
  myscript.run();
  
  Console.print("WiFi RX/TX bytes: ");
  while (myscript.available()) {
    char c = myscript.read();
    Console.print(c);
  }
  Console.println();
  Console.flush();
}