Skip to content

Instantly share code, notes, and snippets.

@jadonk
Last active August 29, 2015 14:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jadonk/178f9aa0f96363e4277e to your computer and use it in GitHub Desktop.
Save jadonk/178f9aa0f96363e4277e to your computer and use it in GitHub Desktop.
var dweetio = require('node-dweetio');
var client = new dweetio();
client.listen_for("beagle-at-mit", listener);
var beagle = {};
function listener(dweet) {
// console.log(dweet);
if(!beagle[dweet.content.sn] || !beagle[dweet.content.sn].ip) {
beagle[dweet.content.sn] = {};
beagle[dweet.content.sn].ip = dweet.content.ip;
beagle[dweet.content.sn].timer = setTimeout(onListenerTimeout, 60000);
console.log(dweet.content.sn + " has IP address " + dweet.content.ip);
} else {
clearTimeout(beagle[dweet.content.sn].timer);
beagle[dweet.content.sn].timer = setTimeout(onListenerTimeout, 60000);
}
function onListenerTimeout() {
console.log(dweet.content.sn + " hasn't pinged in a minute");
beagle[dweet.content.sn].ip = null;
}
}
var http = require('http');
var server = http.createServer(onhttp);
server.listen(1337, '127.0.0.1');
function onhttp(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<html><head><title>Beagle at MIT Dweets</title>');
res.write('<script>setTimeout("window.location=\'/\';", 15000);</script></head>');
res.write('<body><h1>Beagle at MIT Dweets</h1>');
for(var i in beagle) {
res.write('<p>' + i);
if(beagle[i].ip) {
res.write(' has IP address ' + beagle[i].ip);
} else {
res.write(' has dropped off');
}
res.write('</p>');
}
res.end('</body></html>');
}
/*
IAP_Sensor_03 - added millis() timer
NOTES:
Consider using http://playground.arduino.cc/Code/Timer
This example connects to an unencrypted Wifi network.
Then it prints the MAC address of the Wifi BoosterPack / LaunchPad,
the IP address obtained, and other network details.
Circuit:
* CC3200 WiFi LaunchPad or CC3100 WiFi BoosterPack
with TM4C or MSP430 LaunchPad
created 13 July 2010 by dlf (Metodo2 srl)
modified 31 May 2012 by Tom Igoe
modified 2 July 2014 by Noah Luskey
modified and repurposed 14 Jan 2015 by Brian DeLacey
*/
#ifndef __CC3200R1M1RGC__
// Do not include SPI for CC3200 LaunchPad
#include <SPI.h>
#endif
#include <WiFi.h>
String buzzerStateString = "0";
//// >>> Change this to match server address in class
char ssid[] = "MIT GUEST"; // your access point
char password[] = ""; // your network password
//// >>> Change three lines to match server address in class
char server[] = "10.189.35.148"; // your hub messaging server
String destinationServer = "10.189.35.148:8008";
String localServerString = "10.189.35.148:8008";
//// >>> Change this information for each sensorThing to team#
String deviceName = "Team1";
///////////////// NO MORE CHANGES NEEDED ////////////////
int serverPort = 8008; // numeric port on your server
char portChar[] = ":8008";
long lastConfigurationCheck= 0; // the last time the device checked in with the mother ship
long configurationDelay = 10000;// the millisecond delay between configuration checks
boolean magnetic_sensor_installed = false;
boolean light_sensor_installed = false; // true on MIT1
boolean big_button_installed = true;
boolean pir_sensor_installed = false;
// most launchpads have a red LED
#define LED RED_LED
#define MAGNO_SWITCH 5
#define LIGHT_SENSOR 6 // analog
#define BIG_BUTTON 7
#define PIR_SENSOR 8
#define BUZZER 9
WiFiClient client;
int val = 0;
void countdown(int looplimit) {
// give the sensors a bit of time to warm up and settle
for (int counter = 0; counter < looplimit; counter++) {
// Serial.println("counting down timer ...");
digitalWrite(LED, LOW); // initialize the LED off by making the voltage LOW
delay(250);
digitalWrite(LED, HIGH); // initialize the LED off by making the voltage LOW
delay(250);
digitalWrite(LED, LOW); // initialize the LED off by making the voltage LOW
};
}
void buzzerOn() {
// analogWrite(BUZZER, 255);
// digitalWrite(BUZZER, HIGH);
// only play buzzer if configuration says to - otherwise it gets annoying!
if (buzzerStateString == "1") {
for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {
// sets the value (range from 0 to 255):
analogWrite(BUZZER, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
}
// actually also play it for MIT IAP all the time even if it gets annoying!
if (buzzerStateString == "0") {
for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {
// sets the value (range from 0 to 255):
analogWrite(BUZZER, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
}
// Serial.println("Attempting buzzerOn() ");
}
void buzzerOff() {
// analogWrite(BUZZER, 0);
// digitalWrite(BUZZER, LOW);
analogWrite(BUZZER, 0);
// Serial.println("Attempting buzzerOff() ");
}
void toggleBuzzer(){
buzzerOn();
countdown(0);
buzzerOff();
}
void toggleLED(){
digitalWrite(LED, HIGH); // turn the LED on (HIGH is the voltage level)
countdown(1);
digitalWrite(LED, LOW);
}
void checkClientHTTP() { // if there are incoming bytes available
// from the server, read them and print them
String responseString = "";
String copyString = "";
bool copyMode = false;
char leftBracket[] = "[";
char rightBracket[] = "]";
while (client.available()) {
char c = client.read();
if (c==leftBracket[0]) {
copyMode = true;
}
if (copyMode) {
responseString += c; //
// Serial.println(">>>>>> " + responseString);
if (c == rightBracket[0]) {
// Serial.println(buzzerStateString);
// Serial.println("<<<<<<< buzzerStateString");
copyMode = false;
}
if (responseString.charAt(1) == 'b') {
buzzerStateString = responseString.substring(7,8);
Serial.println("<<<<<<< buzzerStateString >>>>>>>> " + buzzerStateString);
}
if (responseString.charAt(1) == 'e') {
int rLength = responseString.length();
int stringLength = rLength - 5;
String serverString = responseString.substring(5,stringLength);
Serial.println("<<<<<<< ethernet address server String >>>>>>>> " + serverString);
}
}
Serial.write(c);
// responseString[0]= c;
// Serial.println(responseString);
}
}
void pnsNameServerFind() {
IPAddress ghost_server;
char buf[] = "1234";
int len = 4;
ghost_server = WiFi.localIP();
// Serial.println(ghost_server);
for (int node = 1; node < 256; node++) {
// String(node).toCharArray(buf, len);
ghost_server[3] = node;
Serial.println(ghost_server);
/*
if (client.connect(ghost_server, serverPort)) {
// if (client.connect("192.168.1.4", serverPort)) {
Serial.println("********* connected to pnsNameServerFind ********* ");
Serial.println(ghost_server);
Serial.println(serverPort);
Serial.println("========= connected to pnsNameServerFind ========= ");
// client.println("GET /hello.html HTTP/1.1");
client.println("GET /resolve HTTP/1.1");
client.println("Host: " + String(ghost_server) + String(portChar));
client.println("Connection: close");
client.println();
// checkClientHTTP(); // if there are incoming bytes available
Serial.println(">>>>>>>>>> connected to pnsNameServerFind <<<<<<<<< ");
//Serial.println("192.168.1." + String(node));
}
*/
}
}
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(115200);
Serial.print("Begin Setup ");
pinMode(LED, OUTPUT);
digitalWrite(LED, LOW); // initialize the LED off by making the voltage LOW
pinMode(BUZZER, OUTPUT);
pinMode(MAGNO_SWITCH, INPUT);
pinMode(PIR_SENSOR, INPUT);
pinMode(BIG_BUTTON, INPUT);
pinMode(LIGHT_SENSOR, INPUT);
toggleBuzzer();
// attempt to connect to Wifi network:
Serial.print("Attempting to connect to Network named: ");
// print the network name (SSID);
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
WiFi.begin(ssid); // begin
while ( WiFi.status() != WL_CONNECTED) {
// print dots while we wait to connect
Serial.print(".");
delay(300);
}
Serial.println("\nYou're connected to the network");
Serial.println("Waiting for an ip address");
while (WiFi.localIP() == INADDR_NONE) {
// print dots while we wait for an ip addresss
Serial.print(".");
delay(300);
}
Serial.println("\nIP Address obtained");
// by now we have a WiFi address - WiFi.localIP()
// search within last octet of our sub-network
// pnsNameServerFind(); TBD - work on this to auto-select server
if (client.connect(server, serverPort)) {
Serial.println("connected to server");
Serial.println(server);
Serial.println(serverPort);
Serial.println("SETUP CONNECTed to server below");
Serial.println("SETUP CONNECTed to server above");
// Make a HTTP request:
client.println("GET /hello.html HTTP/1.1");
// client.println("GET /alert HTTP/1.1");
// client.println("Host: 192.168.1.18:8008");
// client.println("Host: " + localServerString);
client.println("Connection: close");
client.println();
}
else {
Serial.println("SETUP CANNOT FIND server below");
printCurrentNet();
printWifiData();
Serial.println("SETUP CANNOT FIND server above");
}
lastConfigurationCheck = millis(); // initialize
// Print out the status
printCurrentNet();
printWifiData();
}
void loop() {
// printCurrentNet();
// printWifiData();
checkClientHTTP(); // if there are incoming bytes available
checkConfiguration(); // run through and check configuration and sensors
if (big_button_installed)
checkBUTTON();
if (light_sensor_installed)
checkLightSensor();
if (magnetic_sensor_installed)
checkMagnet();
if (pir_sensor_installed)
checkPIR();
}
void sendMsgViaHTTP(String myString) {
Serial.println("sendAlertViaHTTP ...");
if (client.connect(server, serverPort)) {
Serial.println("connected to server");
// Make a HTTP request:
// client.println("GET /hello.html HTTP/1.1");
if (myString == "pir") {
// client.println("GET /alert/pir/office HTTP/1.1");
client.println("GET /alert/pir/" + deviceName + " HTTP/1.1");
}
else
if (myString == "magnet") {
// client.println("GET /alert/magnet/office HTTP/1.1");
client.println("GET /alert/magnet/" + deviceName + " HTTP/1.1");
}
else
if (myString == "button") {
// client.println("GET /alert/button/office HTTP/1.1");
// This really should be a button message / but server not set
client.println("GET /alert/button/" + deviceName + " HTTP/1.1");
}
else
if (myString == "configure") {
// client.println("GET /alert/configure HTTP/1.1");
client.println("GET /alert/configure/" + deviceName + " HTTP/1.1");
}
else // really should never hit this case ...
client.println("GET /hello.html HTTP/1.1");
client.println("Host: " + localServerString);
client.println("Connection: close");
client.println();
}
else {
// Serial.println("LOST SERVER below");
// printCurrentNet();
// printWifiData();
// Serial.println("LOST SERVER above");
}
countdown(3); // give sensors time to settle down
}
void printPIR(int val) {
Serial.print("printPIR: ");
Serial.println(val);
}
void checkPIR() {
String alertType = "pir";
val = digitalRead(PIR_SENSOR);
if (val == HIGH) {
toggleBuzzer();
toggleLED();
sendMsgViaHTTP(alertType);
}
// printPIR(val);
}
void checkBUTTON() {
String alertType = "button";
val = digitalRead(BIG_BUTTON);
if (val == LOW) {
toggleBuzzer();
toggleLED();
sendMsgViaHTTP(alertType);
}
// printPIR(val);
}
void printMagnet(int val) {
Serial.print("printMagnet: ");
Serial.println(val);
}
void checkMagnet() {
String alertType = "magnet";
val = digitalRead(MAGNO_SWITCH);
if (val == LOW) {
toggleBuzzer();
toggleLED();
sendMsgViaHTTP(alertType);
}
// printMagnet(val);
}
void checkLightSensor(){
String alertType = "lights";
val = analogRead(LIGHT_SENSOR);
/*
if (val> 4000)
Serial.println(val);
if (val< 1500)
Serial.println(val);
*/
/*
if (val == LOW) {
toggleBuzzer();
toggleLED();
sendMsgViaHTTP(alertType);
}
*/
}
void checkConfiguration() {
long currentTimeMillis;
currentTimeMillis = millis();
// Serial.print("time is " + currentTimeMillis);
if ((currentTimeMillis - lastConfigurationCheck) > configurationDelay) {
sendMsgViaHTTP("configure"); // String alertType = "configure" ;
Serial.println("$$$ sent onfiguration check message $$$$ ");
lastConfigurationCheck = currentTimeMillis;
}
}
void printWifiData() {
// print your WiFi IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
Serial.println(ip);
// print your MAC address:
byte mac[6];
WiFi.macAddress(mac);
Serial.print("MAC address: ");
Serial.print(mac[5], HEX);
Serial.print(":");
Serial.print(mac[4], HEX);
Serial.print(":");
Serial.print(mac[3], HEX);
Serial.print(":");
Serial.print(mac[2], HEX);
Serial.print(":");
Serial.print(mac[1], HEX);
Serial.print(":");
Serial.println(mac[0], HEX);
}
void printCurrentNet() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print the MAC address of the router you're attached to:
byte bssid[6];
WiFi.BSSID(bssid);
Serial.print("BSSID: ");
Serial.print(bssid[5], HEX);
Serial.print(":");
Serial.print(bssid[4], HEX);
Serial.print(":");
Serial.print(bssid[3], HEX);
Serial.print(":");
Serial.print(bssid[2], HEX);
Serial.print(":");
Serial.print(bssid[1], HEX);
Serial.print(":");
Serial.println(bssid[0], HEX);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.println(rssi);
// print the encryption type:
byte encryption = WiFi.encryptionType();
Serial.print("Encryption Type:");
Serial.println(encryption, HEX);
Serial.println();
}
sed -i '/^#auto wlan0/s/^#auto wlan0/auto ra0/' /etc/network/interfaces
sed -i '/^#iface wlan0/s/^#iface wlan0 inet dhcp/iface ra0 inet dhcp/' /etc/network/interfaces
sed -i '/^#.*wpa-ssid/s/^#.*$/wireless-essid "MIT GUEST"/' /etc/network/interfaces
apt-get install -y avahi-discover libnss-mdns
apt-get update
apt-get install -y curl
curl https://gist.githubusercontent.com/anonymous/c31234b1756b8877fe41/raw/a85da8f6a695534d10385bdf0cc53b89c24c952e/ssh.service > /etc/avahi/services/ssh.service
sed -i "s/XXXXXXXX/`cat /sys/devices/bone_capemgr.*/baseboard/serial-number`/" /etc/avahi/services/ssh.service
systemctl restart avahi-daemon.service
sed -i "s/^exit 0/dart \/root\/send_net_info.dart \&\nexit 0/" /etc/rc.local
import 'dart:io';
import 'dart:async';
import 'dart:convert';
String serialnofile = "/sys/devices/bone_capemgr.9/baseboard/serial-number";
String mysn = "";
String myip = "";
int myport = 8080;
String servername = "dweet.io";
int serverport = 80;
String senduri = "/dweet/for/beagle-at-mit";
String listenuri = "/listen/for/dweets/from/beagle-at-mit";
void main() {
//setupPins();
serveUpdates();
readSerialNo();
var duration = new Duration(seconds: 30);
var timer = new Timer.periodic(duration, onTimer);
readIPAndSendStatus();
}
void onTimer(timer) {
readIPAndSendStatus();
}
void readSerialNo() {
var file = new File('${serialnofile}');
Future<String> finishedReading = file.readAsString(encoding: ASCII);
void saveSerialNo(String serialno) {
mysn = serialno.trim();
print("mysn = " + mysn);
}
void onSecondError(error) {
mysn = "N/A";
print("mysn = " + mysn);
}
void onError(error) {
print('Using /tmp/serialno for the serial number');
var file2 = new File('/tmp/serialno');
Future<String> finishedReading2 = file2.readAsString(encoding: ASCII);
finishedReading2.then(saveSerialNo)
.catchError(onSecondError);
}
finishedReading.then(saveSerialNo)
.catchError(onError);
}
void readIPAndSendStatus() {
String adapter = "ra0";
String ipStart = "inet addr:";
int ipStartLen = 10;
String ipEnd = ' Bcast';
Future<ProcessResult> finished = Process.run('ifconfig', [adapter]);
void sendStatus() {
Future<Socket> connection = Socket.connect(servername, serverport);
void onConnect(Socket socket) {
String uri = '${senduri}?sn=${mysn}&ip=${myip}';
String indexRequest = 'GET ${uri}'
' HTTP/1.1\nConnection: close\n\n';
print('http://${socket.remoteAddress.address}${uri}');
//print(indexRequest);
//print('Sender connected to: '
// '${socket.remoteAddress.address}:${socket.remotePort}');
void onSocketData(data) {
//print('send: ' + new String.fromCharCodes(data).trim());
}
void onSocketDone() {
//print("Done");
socket.destroy();
}
socket.listen(onSocketData, onDone: onSocketDone);
socket.write(indexRequest);
}
void handleError(error) {
print('Send to dweet.io failed.');
}
connection.then(onConnect)
.catchError(handleError);
}
void onIfconfig(ProcessResult results) {
//print(results.stdout);
// If we are on Jason's Mac
if(false) {
adapter = 'en0';
ipStart = 'inet ';
ipStartLen = 5;
ipEnd = 'netmask';
}
var start = results.stdout.indexOf(ipStart)+ipStartLen;
var end = results.stdout.indexOf(ipEnd);
if(start > 0 && end > start) {
String ip = results.stdout.substring(start, end);
if(ip != myip) {
myip = ip;
print('myip = ' + myip);
}
}
sendStatus();
}
finished.then(onIfconfig);
}
void serveUpdates() {
var beagle = {};
Future<HttpServer> myserver = HttpServer.bind(InternetAddress.ANY_IP_V4, myport);
void serverConnect(HttpServer server) {
print("Serving at ${server.address}:${server.port}");
void onRequest(HttpRequest request) {
var res = request.response;
res.headers.contentType = new ContentType("text", "html", charset: "utf-8");
res.write('<html><head><title>Beagle at MIT Dweets</title>');
res.write('<script>setTimeout("window.location=\'/\';", 15000);</script></head>');
res.write('<body><h1>Beagle at MIT Dweets</h1>');
for(var i in beagle.keys) {
res.write('<p>' + i);
if(beagle[i]['ip'] != "") {
res.write(' has IP address ' + beagle[i]['ip']);
} else {
res.write(' has dropped off');
}
res.write('</p>');
}
res.write('</body></html>');
res.close();
}
server.listen(onRequest);
}
void serverError(error) {
print("Error starting my server");
}
myserver.then(serverConnect)
.catchError(serverError);
void getUpdates() {
Future<Socket> connection = Socket.connect(servername, serverport);
void onConnect(Socket socket) {
String indexRequest = 'GET ${listenuri}'
' HTTP/1.1\nConnection: close\n\n';
print('http://${socket.remoteAddress.address}${listenuri}');
//print(indexRequest);
//print('Listener connected to: '
// '${socket.remoteAddress.address}:${socket.remotePort}');
void onSocketData(data) {
String msg = new String.fromCharCodes(data).trim();
//print('listen: ' + msg);
var start = msg.indexOf('"{');
while(start > 0) {
var end = msg.indexOf('}"')+2;
String jsonMsg;
var newData;
try {
jsonMsg = msg.substring(start, end);
newData = JSON.decode(JSON.decode(jsonMsg));
//print('newData = ' + JSON.encode(newData));
// Add the entry
if(newData['content']['sn'] != "") {
var sn = newData['content']['sn'];
var ip = newData['content']['ip'];
print("Adding ${sn} = ${ip}");
beagle[sn] = {};
beagle[sn]['ip'] = ip;
}
// Point to the end
msg = msg.substring(end);
start = msg.indexOf('"{');
} catch(ex) {
break;
}
}
}
void onSocketDone() {
//print("Server providing messages closed socket");
socket.destroy();
}
socket.listen(onSocketData, onDone: onSocketDone);
socket.write(indexRequest);
}
void handleError(error) {
print('Send to dweet.io failed.');
}
connection.then(onConnect)
.catchError(handleError);
}
getUpdates();
}
void setupPins() {
var setupIndex = 0;
var setupOperations = [
{ 'cmd': 'config-pin', 'args': ['overlay', 'cape-universaln'] },
{ 'cmd': 'config-pin', 'args': ['overlay', 'BB-ADC'] },
//{ 'cmd': 'config-pin', 'args': ['p9.14', 'gpio'] },
//{ 'file': '/sys/class/gpio/gpio50/direction', 'data': 'out' },
//{ 'file': '/sys/class/gpio/gpio50/value', 'data': '1' },
{ 'file': '/sys/class/pwm/export', 'data': '3' },
{ 'file': '/sys/class/pwm/pwm3/polarity', 'data': '1' },
{ 'file': '/sys/class/pwm/pwm3/period_ns', 'data': '4000000' },
{ 'file': '/sys/class/pwm/pwm3/duty_ns', 'data': '0' },
{ 'file': '/sys/class/pwm/pwm3/run', 'data': '1' },
{ 'cmd': 'config-pin', 'args': ['p9.14', 'pwm'] },
];
void onDone(ProcessResult results) {
setupIndex++;
if(setupOperations[setupIndex]) {
setupPins();
}
}
void onError(error) {
String err = 'Setup failed executing step ' + setupIndex;
print(err);
throw err;
}
if(setupOperations[setupIndex].containsKey('cmd')) {
var cmd = setupOperations[setupIndex].cmd;
var args = setupOperations[setupIndex].args;
Future<ProcessResult> finished = Process.run(cmd, args);
finished.then(onDone).catchError(onError);
}
}
double readADC() {
String ADCfile = '/sys/bus/iio/devices/iio\:device0/in_voltage5_raw';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment