<commit_before>/**
 * @fileoverview Bootstrapper for local development.
 *
 * This script can be used during development instead of the compiled firebase-simple-login.js.
 * It pulls in the raw source files, so no compilation step is required (though if you
 * change any dependencies, e.g. by adding goog.require statements, you'll need to
 * run compile-js.sh to rebuild deps.js)
 *
 * This script pulls in google closure's base.js and our dependencies file
 * automatically. All other required scripts will be pulled in based on goog.require
 * statements.
 */

// Figure out the base path of firebase-simple-login-local.js.
var basePath = null;
var scripts = document.getElementsByTagName('script');
for (var i = scripts.length - 1; i >= 0; i--) {
  var src = scripts[i].src;
  var l = src.indexOf('firebase-simple-login-local.js');
  if (l != -1) {
    basePath = src.substr(0, l);
    break;
  }
}

if (basePath === null)
  throw "Couldn't determine location of firebase-simple-login-local.js.  WHAT DID YOU DO!?!?!";

document.write('<script type="text/javascript" src="' + basePath + '../../build/closure/library/closure/goog/base.js"></script>');
document.write('<script type="text/javascript" src="' + basePath + '../deps.js"></script>');
document.write('<script type="text/javascript" src="' + basePath + 'firebase-simple-login-require.js"></script>');
<commit_msg>Correct local references when loading uncompiled source<commit_after>/**
 * @fileoverview Bootstrapper for local development.
 *
 * This script can be used during development instead of the compiled firebase-simple-login.js.
 * It pulls in the raw source files, so no compilation step is required (though if you
 * change any dependencies, e.g. by adding goog.require statements, you'll need to
 * run compile-js.sh to rebuild deps.js)
 *
 * This script pulls in google closure's base.js and our dependencies file
 * automatically. All other required scripts will be pulled in based on goog.require
 * statements.
 */

// Figure out the base path of firebase-simple-login-local.js.
var basePath = null;
var scripts = document.getElementsByTagName('script');
for (var i = scripts.length - 1; i >= 0; i--) {
  var src = scripts[i].src;
  var l = src.indexOf('firebase-simple-login-local.js');
  if (l != -1) {
    basePath = src.substr(0, l);
    break;
  }
}

if (basePath === null)
  throw "Couldn't determine location of firebase-simple-login-local.js.  WHAT DID YOU DO!?!?!";

document.write('<script type="text/javascript" src="' + basePath + '../../lib/closure/library/closure/goog/base.js"></script>');
document.write('<script type="text/javascript" src="' + basePath + '../deps.js"></script>');
document.write('<script type="text/javascript" src="' + basePath + 'firebase-simple-login-require.js"></script>');
<|endoftext|>


<commit_before>/**
 *
 * @license
 * Copyright (C) 2016 Joseph Roque
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @author Joseph Roque
 * @file BusCampusDetails.js
 * @providesModule BusCampusDetails
 * @description Displays a campus' location on a map, relative to a user's location, as well as a list of the stops
 *              near the campus.
 *
 * @flow
 */
'use strict';

// React imports
import React from 'react';
import {
  StyleSheet,
  View,
} from 'react-native';

// Type imports
import type {
  LatLong,
  LatLongDelta,
  TransitCampus,
  TransitStop,
  University,
} from 'types';

// Type definition for component props.
type Props = {
  campusColor: string,
  campusName: string,
};

// Type definition for component state.
type State = {
  campus: ?TransitCampus,
  region: ?(LatLong & LatLongDelta),
};

// Type definition for markers to be placed on the map.
type MapMarker = {
  title: string,
  desc: string,
  id: string,
  latlng: {
    latitude: number,
    longitude: number,
  },
};

// Imports
const Configuration = require('Configuration');
const DisplayUtils = require('DisplayUtils');
const MapView = require('react-native-maps');
const StopDetails = require('StopDetails');

class BusCampusDetails extends React.Component {

  /**
   * Properties which the parent component should make available to this component.
   */
  static propTypes = {
    campusColor: React.PropTypes.string.isRequired,
    campusName: React.PropTypes.string.isRequired,
  };

  /**
   * Define type for the component state.
   */
  state: State;

  /**
   * Pass props and declares initial state.
   *
   * @param {Props} props properties passed from container to this component.
   */
  constructor(props: Props) {
    super(props);

    this.state = {
      campus: null,
      region: null,
    };

    // Explicitly binding 'this' to all methods that need it
    (this:any)._getCampusMap = this._getCampusMap.bind(this);
    (this:any)._getCampusStops = this._getCampusStops.bind(this);
    (this:any)._loadCampusInfo = this._loadCampusInfo.bind(this);
  }

  /**
   * If the campus details have not been loaded, then loads them.
   */
  componentDidMount(): void {
    if (this.state.campus == null) {
      Configuration.init()
          .then(this._loadCampusInfo())
          .catch(err => console.error('Configuration could not be initialized for bus campus details.', err));
    }
  }

  /**
   * Invoked when the user selects a stop.
   *
   * @param {?TransitStop} stop properties of the selected stop.
   */
  _busStopSelected(stop: ?TransitStop): void {
    if (stop == null) {
      this.setState({
        region: null,
      });
    } else {
      this.setState({
        region: {
          latitude: stop.lat,
          longitude: stop.long,
          latitudeDelta: 0.005,
          longitudeDelta: 0.005,
        },
      });
    }
  }

  /**
   * Renders a map with a list of markers to denote bus stops near the campus.
   *
   * @returns {ReactElement<any>} a {MapView} with a list of markers placed at the stops on the campus.
   */
  _getCampusMap(): ReactElement<any> {
    const markers: Array<MapMarker> = [];
    let lat: number = 0;
    let long: number = 0;
    let initialRegion: LatLong & LatLongDelta;

    if (this.state.campus == null) {
      const university: ?University = Configuration.getUniversity();
      if (university == null) {
        initialRegion = {
          latitude: 45.4222,
          longitude: -75.6824,
          latitudeDelta: 0.01,
          longitudeDelta: 0.01,
        };
      } else {
        lat = university.lat;
        long = university.long;
        initialRegion = {
          latitude: lat,
          longitude: long,
          latitudeDelta: 0.01,
          longitudeDelta: 0.01,
        };
      }
    } else {
      lat = this.state.campus.lat;
      long = this.state.campus.long;
      initialRegion = {
        latitude: lat,
        longitude: long,
        latitudeDelta: 0.01,
        longitudeDelta: 0.01,
      };

      for (let i = 0; i < this.state.campus.stops.length; i++) {
        markers.push({
          title: this.state.campus.stops[i].name,
          desc: this.state.campus.stops[i].code,
          id: this.state.campus.stops[i].id,
          latlng: {
            latitude: this.state.campus.stops[i].lat,
            longitude: this.state.campus.stops[i].long,
          },
        });
      }
    }

    return (
      <MapView
          region={this.state.region || initialRegion}
          style={_styles.map}>
        {markers.map(marker => (
          <MapView.Marker
              coordinate={marker.latlng}
              description={marker.desc}
              key={marker.id}
              title={marker.title} />
        ))}
      </MapView>
    );
  }

  /**
   * Returns a view containing a header and list with the stops surrounding the campus provided by
   * {this.props.campusName}.
   *
   * @returns {ReactElement<any>} a {Stops} view with details about the various stops on the campus, or an empty view
   */
  _getCampusStops(): ReactElement<any> {
    if (this.state.campus == null) {
      return (
        <View style={_styles.container} />
      );
    } else {
      return (
        <StopDetails
            backgroundIsDark={DisplayUtils.isColorDark(this.props.campusColor)}
            campus={this.state.campus}
            campusName={this.props.campusName}
            onStopSelected={this._busStopSelected.bind(this)} />
      );
    }
  }

  /**
   * Retrieves data about the campus provided as {this.props.campusName}.
   */
  _loadCampusInfo(): void {
    Configuration.getConfig('/transit_stops.json')
        .then(campuses => {
          for (let i = 0; i < campuses.length; i++) {
            if (campuses[i].id === this.props.campusName) {
              this.setState({
                campus: campuses[i],
              });
            }
          }
        })
        .catch(err => console.error('Could not get /transit_stop.json.', err));
  }

  /**
   * Renders a map and list of routes and stop times at the various stops.
   *
   * @returns {ReactElement<any>} the hierarchy of views to render.
   */
  render(): ReactElement<any> {
    return (
      <View style={[_styles.container, {backgroundColor: this.props.campusColor}]}>
        <View style={_styles.mapContainer}>
          {this._getCampusMap()}
        </View>
        <View style={_styles.stopsContainer}>
          {this._getCampusStops()}
        </View>
      </View>
    );
  }
}

// Private styles for the component
const _styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  map: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
  mapContainer: {
    flex: 1,
  },
  stopsContainer: {
    flex: 2,
  },
});

module.exports = BusCampusDetails;
<commit_msg>Select bus stop when callout pressed<commit_after>/**
 *
 * @license
 * Copyright (C) 2016 Joseph Roque
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @author Joseph Roque
 * @file BusCampusDetails.js
 * @providesModule BusCampusDetails
 * @description Displays a campus' location on a map, relative to a user's location, as well as a list of the stops
 *              near the campus.
 *
 * @flow
 */
'use strict';

// React imports
import React from 'react';
import {
  StyleSheet,
  View,
} from 'react-native';

// Type imports
import type {
  LatLong,
  LatLongDelta,
  TransitCampus,
  TransitStop,
  University,
} from 'types';

// Type definition for component props.
type Props = {
  campusColor: string,
  campusName: string,
};

// Type definition for component state.
type State = {
  campus: ?TransitCampus,
  region: ?(LatLong & LatLongDelta),
};

// Imports
const Configuration = require('Configuration');
const DisplayUtils = require('DisplayUtils');
const MapView = require('react-native-maps');
const StopDetails = require('StopDetails');

class BusCampusDetails extends React.Component {

  /**
   * Properties which the parent component should make available to this component.
   */
  static propTypes = {
    campusColor: React.PropTypes.string.isRequired,
    campusName: React.PropTypes.string.isRequired,
  };

  /**
   * Define type for the component state.
   */
  state: State;

  /**
   * Pass props and declares initial state.
   *
   * @param {Props} props properties passed from container to this component.
   */
  constructor(props: Props) {
    super(props);

    this.state = {
      campus: null,
      region: null,
    };

    // Explicitly binding 'this' to all methods that need it
    (this:any)._busStopSelected = this._busStopSelected.bind(this);
    (this:any)._getCampusMap = this._getCampusMap.bind(this);
    (this:any)._getCampusStops = this._getCampusStops.bind(this);
    (this:any)._loadCampusInfo = this._loadCampusInfo.bind(this);
  }

  /**
   * If the campus details have not been loaded, then loads them.
   */
  componentDidMount(): void {
    if (this.state.campus == null) {
      Configuration.init()
          .then(this._loadCampusInfo())
          .catch(err => console.error('Configuration could not be initialized for bus campus details.', err));
    }
  }

  /**
   * Invoked when the user selects a stop.
   *
   * @param {?TransitStop} stop properties of the selected stop.
   */
  _busStopSelected(stop: ?TransitStop): void {
    if (stop == null) {
      this.setState({
        region: null,
      });
    } else {
      this.setState({
        region: {
          latitude: stop.lat,
          longitude: stop.long,
          latitudeDelta: 0.005,
          longitudeDelta: 0.005,
        },
      });
    }
  }

  /**
   * Renders a map with a list of markers to denote bus stops near the campus.
   *
   * @returns {ReactElement<any>} a {MapView} with a list of markers placed at the stops on the campus.
   */
  _getCampusMap(): ReactElement<any> {
    let markers: Array<TransitStop> = [];
    let lat: number = 0;
    let long: number = 0;
    let initialRegion: LatLong & LatLongDelta;

    if (this.state.campus == null) {
      const university: ?University = Configuration.getUniversity();
      if (university == null) {
        initialRegion = {
          latitude: 45.4222,
          longitude: -75.6824,
          latitudeDelta: 0.01,
          longitudeDelta: 0.01,
        };
      } else {
        lat = university.lat;
        long = university.long;
        initialRegion = {
          latitude: lat,
          longitude: long,
          latitudeDelta: 0.01,
          longitudeDelta: 0.01,
        };
      }
    } else {
      lat = this.state.campus.lat;
      long = this.state.campus.long;
      initialRegion = {
        latitude: lat,
        longitude: long,
        latitudeDelta: 0.01,
        longitudeDelta: 0.01,
      };

      markers = this.state.campus.stops;
    }

    // TODO: onCalloutPress (below) does not currently work for iOS
    // Follow progress at https://github.com/lelandrichardson/react-native-maps/issues/286

    return (
      <MapView
          region={this.state.region || initialRegion}
          style={_styles.map}>
        {markers.map(stop => (
          <MapView.Marker
              coordinate={{latitude: stop.lat, longitude: stop.long}}
              description={stop.code}
              key={stop.id}
              title={stop.name}
              onCalloutPress={() => this._busStopSelected(stop)} />
        ))}
      </MapView>
    );
  }

  /**
   * Returns a view containing a header and list with the stops surrounding the campus provided by
   * {this.props.campusName}.
   *
   * @returns {ReactElement<any>} a {Stops} view with details about the various stops on the campus, or an empty view
   */
  _getCampusStops(): ReactElement<any> {
    if (this.state.campus == null) {
      return (
        <View style={_styles.container} />
      );
    } else {
      return (
        <StopDetails
            backgroundIsDark={DisplayUtils.isColorDark(this.props.campusColor)}
            campus={this.state.campus}
            campusName={this.props.campusName}
            onStopSelected={this._busStopSelected} />
      );
    }
  }

  /**
   * Retrieves data about the campus provided as {this.props.campusName}.
   */
  _loadCampusInfo(): void {
    Configuration.getConfig('/transit_stops.json')
        .then(campuses => {
          for (let i = 0; i < campuses.length; i++) {
            if (campuses[i].id === this.props.campusName) {
              this.setState({
                campus: campuses[i],
              });
            }
          }
        })
        .catch(err => console.error('Could not get /transit_stop.json.', err));
  }

  /**
   * Renders a map and list of routes and stop times at the various stops.
   *
   * @returns {ReactElement<any>} the hierarchy of views to render.
   */
  render(): ReactElement<any> {
    return (
      <View style={[_styles.container, {backgroundColor: this.props.campusColor}]}>
        <View style={_styles.mapContainer}>
          {this._getCampusMap()}
        </View>
        <View style={_styles.stopsContainer}>
          {this._getCampusStops()}
        </View>
      </View>
    );
  }
}

// Private styles for the component
const _styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  map: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
  mapContainer: {
    flex: 1,
  },
  stopsContainer: {
    flex: 2,
  },
});

module.exports = BusCampusDetails;
<|endoftext|>


<commit_before>'use strict';

// 函数接收另一个函数作为参数：高阶函数

function add(x,y,f){
	return f(x)+f(y);
}

console.log(add(-5,6,Math.abs));

//map Array===>新的Array

function pow(x){
	return x*x;
}

var array = [1,2,3,4,5];

var new_array = array.map(pow);

console.log(new_array);
console.log(new_array.map(String));

//reduce
//Array的reduce()把一个函数作用到Array上
//接收两个参数，reduce把结果和序列的下一个元素做累积计算
//如 [x1,x2,x3,x4].reduce(f) = f(f(f(x1,x2),x3),x4);

var arr = [1,3,5,7,9];
var sum = arr.reduce(function(x,y){
	return x+y;
});

console.log(sum);

function string2int(s){
	if(typeof(s)!=='string'){
		throw 's is not a number';
	}
	var num = {
		'1':1,
		'2':2,
		'3':3,
		'4':4,
		'5':5,
		'6':6,
		'7':7,
		'8':8,
		'9':9,
		'0':0
	}
    var result = Array.from(s).map(function(n){
           return num[n];
    }).reduce(function(x,y){
       return x * 10+ y;
    });
    return result;
}

console.log(string2int('12345'));
console.log(Array.from('12345'));
// console.log(string2int(true));

function normalize(arr) {
    arr.map(function(name){
        return name.charAt(0).toUpperCase()+name.substring(1, name.length).toUpperCase();
    });
}

var str_array = ['1','2','3'];
var r = str_array.map(s=>parseInt(s));

console.log(r);

<commit_msg>update higher order function<commit_after>'use strict';

// 函数接收另一个函数作为参数：高阶函数

function add(x,y,f){
	return f(x)+f(y);
}

console.log(add(-5,6,Math.abs));

//map Array===>新的Array

function pow(x){
	return x*x;
}

var array = [1,2,3,4,5];

var new_array = array.map(pow);

console.log(new_array);
console.log(new_array.map(String));

//reduce
//Array的reduce()把一个函数作用到Array上
//接收两个参数，reduce把结果和序列的下一个元素做累积计算
//如 [x1,x2,x3,x4].reduce(f) = f(f(f(x1,x2),x3),x4);

var arr = [1,3,5,7,9];
var sum = arr.reduce(function(x,y){
	return x+y;
});

console.log(sum);

function string2int(s){
	if(typeof(s)!=='string'){
		throw 's is not a number';
	}
	var num = {
		'1':1,
		'2':2,
		'3':3,
		'4':4,
		'5':5,
		'6':6,
		'7':7,
		'8':8,
		'9':9,
		'0':0
	}
    var result = Array.from(s).map(function(n){
           return num[n];
    }).reduce(function(x,y){
       return x * 10+ y;
    });
    return result;
}

console.log(string2int('12345'));
console.log(Array.from('12345'));
// console.log(string2int(true));

function normalize(arr) {
    arr.map(function(name){
        return name.charAt(0).toUpperCase()+name.substring(1, name.length).toUpperCase();
    });
}

var str_array = ['1','2','3'];
var r = str_array.map(s=>parseInt(s));

console.log(r);

//filter
//接收一个函数，根据函数的返回值是true还是false
//来决定是否保留元素

var nums = [1,2,3,4,5];
var result = nums.filter(function(x){
	return x%2==1;
});

console.log(result);

var stringArray = ['A','','c',null,undefined,' '];
var filterResult = stringArray.filter(function(s){
	return s&&s.trim();
});

console.log(filterResult);

//filter()方法可以接收多个参数

var arr = ['A','B','C'];
var result = arr.filter(function(element,index,self){
     console.log('element:'+element+' index:'+index);
     console.log('self:'+self);
     return true;
});

console.log(result);

//sort
//JS中的Array的sort()方法
//先将所有元素转换为String再排序

var numArray = [10,20,1,2]
var sort = numArray.sort();
console.log(sort);

//sort方法也是高阶函数
var sort2= numArray.sort(function(x,y){
   return x>y?1:(x==y?0:-1);
});
console.log(sort2);

//sort方法会直接对Array进行修改
console.log(numArray);
console.log(sort);
console.log(sort2);

<|endoftext|>


<commit_before>// Enable/disable debugging messages.
var debug = new Debug();
debug.SetEnabled(false);
debug.SetOutput(console.log);
debug.SetLogLevel = Debug.INFO;

/* Includes/Imports */
var path = require('path'); // init path so we can create paths using path.join()
// init app using express to make app a function handler which we can parse on to the HTTP server
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var SerialPort = require('serialport').SerialPort
var dataType = require('./sensor_config')

// Open a connection to a serial port
var serialport = new SerialPort("/dev/ttyUSB0", {
	baudrate: 115200
});
var clientsConnected = 0; // Keep statistics of the amount of connected clients
var currentPack = new Package(); // The package which we are currently building

// Defining the route handler
app.get('/', function(request, response){
	response.sendFile(path.join(__dirname, 'index.html'));
});

// We hook up on the socket.io connection event.
io.on('connection', function(socket){
	clientsConnected++; // increment amount of clients
	console.log('a client connected');
	console.log("Total: " + clientsConnected);
	// Hook up for disconnect event
	socket.on('disconnect', function(){
		clientsConnected--; // decrement amount of clients
		console.log("a client disconnected");
		console.log("Total: " + clientsConnected);
	});
});

// We make the http server listen to port 3000
http.listen(3000, function(){
	console.log('listening on *:3000');
});

// the serial port is opened asynchronously, meaning we are not able to read data
// before the 'open' event has happened.
serialport.on('open', function(){
	console.log('Serial port is now open');

	// Event for received data
	serialport.on('data', function(data){
		// Data has been received.
		ParsePackage(data);
	});
	// Error handling
	serialPort.write("ls\n", function(err, results) {
		console.log('err ' + err);
	});
});
serialport.on('error', function(error){
	console.log(error);
	process.kill();
})

var printDebug = function(msg){
	if (debug)
		console.log(msg);
};

// Parses the data buffer we are receiving from xbee
var ParsePackage = function(data){
	for(i = 0; i < data.length; i++){
		var currentByte = data[i];
		currentPack.AddByte(currentByte);
		if (currentPack.IsFull()){ // our package is ready for dispatch to the client

			// Get the sensor type from the sensor config using the retrieved id from the package
			var sensorType = dataType.sensorConfig[currentPack.GetId()];
			// Create the sensor structure
			var sensor = {
				name: sensorType.name,
				value: currentPack.GetValue().toFixed(2),
				timestamp: new Date().getTime()
			};
			// send data to client
			debug.Print("Package recieved", debug.INFO);
			debug.Print("Id: " + currentPack.GetId(), debug.INFO);
			debug.Print(currentPack.GetBuffer(), debug.INFO);
			debug.Print(sensor, debug.INFO);
			debug.Print();
			io.emit(sensor.name, sensor);
			currentPack = new Package();
		}
	}
};

/* 	Package object for handling data packages.
	Start sequence: 0xA1, 0xB2, 0xC3, 0xD4, 0xE5, 0xF6
	Package structure: byte0 = id, byte1-2 = length of value, rest: Value */
function Package(){
	// gives us the possibility to refer to our variables inside the function
	var self = this;

	// Package id
	self._id = undefined;
	self._buffer = undefined;
	self._bufferIndex = 0;
	self._startSequence = [0xA1, 0xB2, 0xC3, 0xD4, 0xE5, 0xF6];
	self._startSequenceIndex = 0;
	self._isStartSequenceFound = false;
	self._lengthBuffer = undefined;
	self._lengthBufferIndex = 0;

	// public methods
	/*
		AddByte is used for adding a byte to the package.
		Start packages are automatically detected by the AddByte method.
		Several other getter methods are available to retrieve specific fields
		of a package when the package has been fully created.
	*/
	self.AddByte = AddByte;
	function AddByte(newByte){
		if (self._isStartSequenceFound === false){
			if (isPartOfStartSequence(newByte)){
				self._startSequenceIndex++;
				return;
			} else if (self._startSequenceIndex >= self._startSequence.length - 1){
				self._isStartSequenceFound = true;
			} else {
				self._startSequenceIndex = 0;
				self._isStartSequenceFound = false;
				return;
			}
		}

		// We just read the start package and id is undefined. Thus current byte is our package id
		if (self._id === undefined){
			self._id = newByte;
			return;
		}

		// If lengthBuffer is undefined - Add two bytes to lengthBuffer since length is the next 16 bits
		// Initialize the buffer containing the length of the package
		if (self._lengthBuffer === undefined){
			self._lengthBuffer = new Buffer([0x0, 0x0]);
		}
		// add the current byte to the length buffer, if length is not found yet
		if (self._lengthBufferIndex < self._lengthBuffer.length){
			self._lengthBuffer[self._lengthBufferIndex] = newByte;
			self._lengthBufferIndex++;
			return;
		}

		// if buffer in undefined we are about to receive a new package.
		// prepare buffer by initializing it to the proper length
		if (self._buffer === undefined){
			// get buffer length
			var n = self._lengthBuffer.readUInt16BE(0)
			self._buffer = new Buffer(n);
			self._bufferIndex = 0;
		}

		// we are receiving a byte for the package
		if (self._bufferIndex < self._buffer.length){
			self._buffer[self._bufferIndex] = newByte;
			self._bufferIndex++;
		} else { // package is full reset all values
			self._id = undefined;
			self._buffer = undefined;
			self._bufferIndex = 0;
			self._startSequenceIndex = 0;
			self._isStartSequenceFound = false;
			self._lengthBuffer = undefined;
			self._lengthBufferIndex = 0;
		}
	};
	// Gets the id of the data package.
	// This value is the id of the sensor in the Sensor config. Thus it can be used to retrive
	// The sensor structure from this configuration.
	self.GetId = GetId;
	function GetId(){
		return self._id;
	};
	// Gets the length of the buffer
	self.GetLength = GetLength;
	function GetLength(){
		return self._buffer.length;
	};
	// Returns the value of the data package build in the buffer
	self.GetValue = GetValue;
	function GetValue(){
		return self._buffer.readFloatLE(0);
	};
	// Returns the buffer which is begin build in this class.
	self.GetBuffer = GetBuffer;
	function GetBuffer(){
		return self._buffer;
	};
	// Determines whether all bytes of the package has been added.
	self.IsFull = IsFull;
	function IsFull(){
		if (self._buffer === undefined){
			return false;
		}

		if (self._bufferIndex === self._buffer.length) {
			return true;
		} else {
			return false;
		}
	};

	// private methods
	// Determines whether the parsed byte is part of the start sequence at the correct index
	var isPartOfStartSequence = function(currentByte){
		if (currentByte === self._startSequence[self._startSequenceIndex]){
			return true;
		}
		return false;
	};

	return self;
};

function Debug(){
	var self = this;

	self.ERROR = 1
	self.WARNING = 2;
	self.INFO = 3;
	self.VERBOSE = 4;

	self.Enabled = false;
	self.Level = self.ERROR;
	self.Out = console.log;

	self.Print = Print;
	function Print(msg, loglevel){
		if (self.Enabled && loglevel >= self.Level)
			self.Out(createTimeStamp() + " " + msg);
	};
	self.SetOutput = SetOutput;
	function SetOutput(output){
		self.Out = output;
	};
	self.SetEnabled = SetEnabled;
	function SetEnabled(enabled){
		self.Enabled = enabled;
	};
	self.SetLogLevel = SetLogLevel;
	function SetLogLevel(loglevel){
		if (loglevel <= 4)
			self.Level = loglevel;
		else
			console.log("Debug: loglevel is out of bounds");
			process.kill();
	};

	var createTimeStamp = function(){
		var d = new Date();
		var timestamp =  "[" + ensureTwoDigits(d.getFullYear()) + "-" + ensureTwoDigits((d.getMonth()+1)) + "-" + ensureTwoDigits(d.getDate()) + " " +
						ensureTwoDigits(d.getHours()) + "-" + ensureTwoDigits(d.getMinutes()) + "-" + ensureTwoDigits(d.getSeconds()) + "]";
		return timestamp;
	};
	var ensureTwoDigits = function(number){
		return ("0" + (number)).slice(-2);
	};
}
<commit_msg>Editted route handler<commit_after>// Enable/disable debugging messages.
var debug = new Debug();
debug.SetEnabled(false);
debug.SetOutput(console.log);
debug.SetLogLevel = Debug.INFO;

/* Includes/Imports */
var path = require('path'); // init path so we can create paths using path.join()
// init app using express to make app a function handler which we can parse on to the HTTP server
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var SerialPort = require('serialport').SerialPort
var dataType = require('./sensor_config')

// Open a connection to a serial port
var serialport = new SerialPort("/dev/ttyUSB0", {
	baudrate: 115200
});
var clientsConnected = 0; // Keep statistics of the amount of connected clients
var currentPack = new Package(); // The package which we are currently building

// Defining the route handlers
app.get('/', function(request, response){
	response.sendFile(path.join(__dirname, 'index.html'));
});
app.get('/public/jquery-2.1.1.min.js', function(req, res){
  res.sendFile(path.join(__dirname, '/public/jquery-2.1.1.min.js'));
});
app.get('/public/highcharts.js', function(req, res){
  res.sendFile(path.join(__dirname, '/public/highcharts.js'));
});
app.get('/public/highcharts-more.js', function(req, res){
  res.sendFile(path.join(__dirname, '/public/highcharts-more.js'));
});

// We hook up on the socket.io connection event.
io.on('connection', function(socket){
	clientsConnected++; // increment amount of clients
	console.log('a client connected');
	console.log("Total: " + clientsConnected);
	// Hook up for disconnect event
	socket.on('disconnect', function(){
		clientsConnected--; // decrement amount of clients
		console.log("a client disconnected");
		console.log("Total: " + clientsConnected);
	});
});

// We make the http server listen to port 3000
http.listen(3000, function(){
	console.log('listening on *:3000');
});

// the serial port is opened asynchronously, meaning we are not able to read data
// before the 'open' event has happened.
serialport.on('open', function(){
	console.log('Serial port is now open');

	// Event for received data
	serialport.on('data', function(data){
		// Data has been received.
		ParsePackage(data);
	});
	// Error handling
	serialPort.write("ls\n", function(err, results) {
		console.log('err ' + err);
	});
});
serialport.on('error', function(error){
	console.log(error);
	process.kill();
})

var printDebug = function(msg){
	if (debug)
		console.log(msg);
};

// Parses the data buffer we are receiving from xbee
var ParsePackage = function(data){
	for(i = 0; i < data.length; i++){
		var currentByte = data[i];
		currentPack.AddByte(currentByte);
		if (currentPack.IsFull()){ // our package is ready for dispatch to the client

			// Get the sensor type from the sensor config using the retrieved id from the package
			var sensorType = dataType.sensorConfig[currentPack.GetId()];
			// Create the sensor structure
			var sensor = {
				name: sensorType.name,
				value: currentPack.GetValue().toFixed(2),
				timestamp: new Date().getTime()
			};
			// send data to client
			debug.Print("Package recieved", debug.INFO);
			debug.Print("Id: " + currentPack.GetId(), debug.INFO);
			debug.Print(currentPack.GetBuffer(), debug.INFO);
			debug.Print(sensor, debug.INFO);
			debug.Print();
			io.emit(sensor.name, sensor);
			currentPack = new Package();
		}
	}
};

/* 	Package object for handling data packages.
	Start sequence: 0xA1, 0xB2, 0xC3, 0xD4, 0xE5, 0xF6
	Package structure: byte0 = id, byte1-2 = length of value, rest: Value */
function Package(){
	// gives us the possibility to refer to our variables inside the function
	var self = this;

	// Package id
	self._id = undefined;
	self._buffer = undefined;
	self._bufferIndex = 0;
	self._startSequence = [0xA1, 0xB2, 0xC3, 0xD4, 0xE5, 0xF6];
	self._startSequenceIndex = 0;
	self._isStartSequenceFound = false;
	self._lengthBuffer = undefined;
	self._lengthBufferIndex = 0;

	// public methods
	/*
		AddByte is used for adding a byte to the package.
		Start packages are automatically detected by the AddByte method.
		Several other getter methods are available to retrieve specific fields
		of a package when the package has been fully created.
	*/
	self.AddByte = AddByte;
	function AddByte(newByte){
		if (self._isStartSequenceFound === false){
			if (isPartOfStartSequence(newByte)){
				self._startSequenceIndex++;
				return;
			} else if (self._startSequenceIndex >= self._startSequence.length - 1){
				self._isStartSequenceFound = true;
			} else {
				self._startSequenceIndex = 0;
				self._isStartSequenceFound = false;
				return;
			}
		}

		// We just read the start package and id is undefined. Thus current byte is our package id
		if (self._id === undefined){
			self._id = newByte;
			return;
		}

		// If lengthBuffer is undefined - Add two bytes to lengthBuffer since length is the next 16 bits
		// Initialize the buffer containing the length of the package
		if (self._lengthBuffer === undefined){
			self._lengthBuffer = new Buffer([0x0, 0x0]);
		}
		// add the current byte to the length buffer, if length is not found yet
		if (self._lengthBufferIndex < self._lengthBuffer.length){
			self._lengthBuffer[self._lengthBufferIndex] = newByte;
			self._lengthBufferIndex++;
			return;
		}

		// if buffer in undefined we are about to receive a new package.
		// prepare buffer by initializing it to the proper length
		if (self._buffer === undefined){
			// get buffer length
			var n = self._lengthBuffer.readUInt16BE(0)
			self._buffer = new Buffer(n);
			self._bufferIndex = 0;
		}

		// we are receiving a byte for the package
		if (self._bufferIndex < self._buffer.length){
			self._buffer[self._bufferIndex] = newByte;
			self._bufferIndex++;
		} else { // package is full reset all values
			self._id = undefined;
			self._buffer = undefined;
			self._bufferIndex = 0;
			self._startSequenceIndex = 0;
			self._isStartSequenceFound = false;
			self._lengthBuffer = undefined;
			self._lengthBufferIndex = 0;
		}
	};
	// Gets the id of the data package.
	// This value is the id of the sensor in the Sensor config. Thus it can be used to retrive
	// The sensor structure from this configuration.
	self.GetId = GetId;
	function GetId(){
		return self._id;
	};
	// Gets the length of the buffer
	self.GetLength = GetLength;
	function GetLength(){
		return self._buffer.length;
	};
	// Returns the value of the data package build in the buffer
	self.GetValue = GetValue;
	function GetValue(){
		return self._buffer.readFloatLE(0);
	};
	// Returns the buffer which is begin build in this class.
	self.GetBuffer = GetBuffer;
	function GetBuffer(){
		return self._buffer;
	};
	// Determines whether all bytes of the package has been added.
	self.IsFull = IsFull;
	function IsFull(){
		if (self._buffer === undefined){
			return false;
		}

		if (self._bufferIndex === self._buffer.length) {
			return true;
		} else {
			return false;
		}
	};

	// private methods
	// Determines whether the parsed byte is part of the start sequence at the correct index
	var isPartOfStartSequence = function(currentByte){
		if (currentByte === self._startSequence[self._startSequenceIndex]){
			return true;
		}
		return false;
	};

	return self;
};

function Debug(){
	var self = this;

	self.ERROR = 1
	self.WARNING = 2;
	self.INFO = 3;
	self.VERBOSE = 4;

	self.Enabled = false;
	self.Level = self.ERROR;
	self.Out = console.log;

	self.Print = Print;
	function Print(msg, loglevel){
		if (self.Enabled && loglevel >= self.Level)
			self.Out(createTimeStamp() + " " + msg);
	};
	self.SetOutput = SetOutput;
	function SetOutput(output){
		self.Out = output;
	};
	self.SetEnabled = SetEnabled;
	function SetEnabled(enabled){
		self.Enabled = enabled;
	};
	self.SetLogLevel = SetLogLevel;
	function SetLogLevel(loglevel){
		if (loglevel <= 4)
			self.Level = loglevel;
		else
			console.log("Debug: loglevel is out of bounds");
			process.kill();
	};

	var createTimeStamp = function(){
		var d = new Date();
		var timestamp =  "[" + ensureTwoDigits(d.getFullYear()) + "-" + ensureTwoDigits((d.getMonth()+1)) + "-" + ensureTwoDigits(d.getDate()) + " " +
						ensureTwoDigits(d.getHours()) + "-" + ensureTwoDigits(d.getMinutes()) + "-" + ensureTwoDigits(d.getSeconds()) + "]";
		return timestamp;
	};
	var ensureTwoDigits = function(number){
		return ("0" + (number)).slice(-2);
	};
}
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var path = require('path'); // init path so we can create paths using path.join()
var os = require('os');
// init app using express to make app a function handler which we can parse on to the HTTP server
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var SerialPort = require('serialport').SerialPort;
var schema = require("./schema");

require("serialport").list(function (err, ports) {
    ports.forEach(function(port) {
        console.log(port);
    });
});

// Open a connection to a serial port
var ports = {
    "linux": "/dev/ttyUSB0",
    "darwin": "/dev/tty.usbserial-A900FLLE",
    "win32": "COM3",
};
var serialport = new SerialPort(ports[os.platform()], {
    baudrate: 115200,
    parser: require('./parser')(),
});
var clientsConnected = 0; // Keep statistics of the amount of connected clients

app.use(express.static(path.join(__dirname, 'public')));

// We hook up on the socket.io connection event.
io.on('connection', function(socket){
    clientsConnected++; // increment amount of clients
    console.log('a client connected');
    console.log("Total: " + clientsConnected);
    // Hook up for disconnect event
    socket.on('disconnect', function(){
        clientsConnected--; // decrement amount of clients
        console.log("a client disconnected");
        console.log("Total: " + clientsConnected);
    });

    socket.on('download', function() {
        var buf = new Buffer(3); // 3: uint8 - uint16 -
        buf.writeUInt8(0x01, 0);        //Write 1 offset by 0
        buf.writeUInt16LE(0x0001, 1);   //Write 0 and 3 offset by 1
        serialport.write(buf);
    });
});

var sendPackage = (function(){
	var pktList = [];
	var lastSend = Date.now();
	var timeout = null;
	return function(key, pkt) {
		if (timeout !== null) clearTimeout(timeout);
		pktList.push(pkt);
		var timeoutTime = 100;
		var now = Date.now();
		var flush = function() {
			io.emit(key, pktList);
			pktList = [];
			lastSend = now;
		}
		if (now - lastSend > timeoutTime) {
			flush();
		} else {
			timeout = setTimeout(flush, timeoutTime);
		}
	};
})();

// We make the http server listen to port 3000
var PORT = 3000;
http.listen(PORT, function(){
    console.log('listening on port', PORT);
});

// the serial port is opened asynchronously, meaning we are not able to read data
// before the 'open' event has happened.
serialport.on('open', function(error) {
    if (error) console.log(error);
    console.log('Serial port is now open');

    // Event for received data
    serialport.on('data', function(data){
        schema.unpack(data, function(err, pkt) {
            if (err) throw err;
            console.log(pkt, ",");
            if (pkt.name === "request log") {
                pkt.value = require("./log2csv").toCsv(pkt.value);
            }
            sendPackage('data', pkt);
        });
    });

});
serialport.on('error', function(error){
    //throw new Error(error);
    console.log(error);
});

var debug = true;
//Debug functions
if(debug) {
    setInterval(function() {
        sendPackage('data', {
            name: 'RoadSpeed (km/h)',
            value: (Math.random() - 0.5) * 20
        });
    }, 10);

    setInterval(function() {
        sendPackage('data', {
            name: 'GX',
            value: Math.floor(Math.random() * 3)+2.5
        });
    }, 10);

    setInterval(function() {
        sendPackage('data', {
            name: 'GY',
            value: Math.floor(Math.random() * 3)
        });
    }, 10);

    setInterval(function() {
        sendPackage('data', {
            name: 'GZ',
            value: Math.floor(Math.random() * 3)-2.5
        });
    }, 10);

	// for (var i = 0; i < 50; i++) {
	// 	(function(i){
	// 		setInterval(function() {
	// 			sendPackage('data', {
	// 				name: 'data-' + i,
	// 				value: Math.floor(Math.random() * i)-2.5
	// 			});
	// 		}, 10);
	// 	})(i)
	// }
}
<commit_msg>Added some more interresting debug data<commit_after>'use strict';

var _ = require('lodash');
var path = require('path'); // init path so we can create paths using path.join()
var os = require('os');
// init app using express to make app a function handler which we can parse on to the HTTP server
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var SerialPort = require('serialport').SerialPort;
var schema = require("./schema");

require("serialport").list(function (err, ports) {
    ports.forEach(function(port) {
        console.log(port);
    });
});

// Open a connection to a serial port
var ports = {
    "linux": "/dev/ttyUSB0",
    "darwin": "/dev/tty.usbserial-A900FLLE",
    "win32": "COM3",
};
var serialport = new SerialPort(ports[os.platform()], {
    baudrate: 115200,
    parser: require('./parser')(),
});
var clientsConnected = 0; // Keep statistics of the amount of connected clients

app.use(express.static(path.join(__dirname, 'public')));

// We hook up on the socket.io connection event.
io.on('connection', function(socket){
    clientsConnected++; // increment amount of clients
    console.log('a client connected');
    console.log("Total: " + clientsConnected);
    // Hook up for disconnect event
    socket.on('disconnect', function(){
        clientsConnected--; // decrement amount of clients
        console.log("a client disconnected");
        console.log("Total: " + clientsConnected);
    });

    socket.on('download', function() {
        var buf = new Buffer(3); // 3: uint8 - uint16 -
        buf.writeUInt8(0x01, 0);        //Write 1 offset by 0
        buf.writeUInt16LE(0x0001, 1);   //Write 0 and 3 offset by 1
        serialport.write(buf);
    });
});

var sendPackage = (function(){
	var pktList = [];
	var lastSend = Date.now();
	var timeout = null;
	return function(key, pkt) {
		if (timeout !== null) clearTimeout(timeout);
		pktList.push(pkt);
		var timeoutTime = 100;
		var now = Date.now();
		var flush = function() {
			io.emit(key, pktList);
			pktList = [];
			lastSend = now;
		}
		if (now - lastSend > timeoutTime) {
			flush();
		} else {
			timeout = setTimeout(flush, timeoutTime);
		}
	};
})();

// We make the http server listen to port 3000
var PORT = 3000;
http.listen(PORT, function(){
    console.log('listening on port', PORT);
});

// the serial port is opened asynchronously, meaning we are not able to read data
// before the 'open' event has happened.
serialport.on('open', function(error) {
    if (error) console.log(error);
    console.log('Serial port is now open');

    // Event for received data
    serialport.on('data', function(data){
        schema.unpack(data, function(err, pkt) {
            if (err) throw err;
            console.log(pkt, ",");
            if (pkt.name === "request log") {
                pkt.value = require("./log2csv").toCsv(pkt.value);
            }
            sendPackage('data', pkt);
        });
    });

});
serialport.on('error', function(error){
    //throw new Error(error);
    console.log(error);
});

var debug = true;
//Debug functions
if(debug) {
    setInterval(function() {
        sendPackage('data', {
            name: 'RoadSpeed (km/h)',
            value: (Math.random() - 0.5) * 20
        });
    }, 10);

    setInterval(function() {
        sendPackage('data', {
            name: 'GX',
            value: Math.floor(Math.random() * 3)+2.5
        });
    }, 10);

    setInterval(function() {
        sendPackage('data', {
            name: 'GY',
            value: Math.floor(Math.random() * 3)
        });
    }, 10);

    setInterval(function() {
        sendPackage('data', {
            name: 'GZ',
            value: Math.floor(Math.random() * 3)-2.5
        });
    }, 10);

	(function(){
		var dt = 0.0;
		setInterval(function() {
			dt += 0.1;
			sendPackage('data', {
				name: 'sine wave',
				value: Math.sin(dt)
			});
		}, 25);
	})();

	(function(){
		var dt = 0.0;
		setInterval(function() {
			dt += 0.1;
			sendPackage('data', {
				name: 'Spike noisy sin',
				value: Math.tan(dt) + Math.sin(dt)
			});
		}, 10);
	})();

	(function(){
		var dt = 0.0;
		setInterval(function() {
			dt += 0.1;
			sendPackage('data', {
				name: 'noisy sine',
				value: Math.sin(dt) * Math.random()
			});
		}, 10);
	})();

	// for (var i = 0; i < 50; i++) {
	// 	(function(i){
	// 		setInterval(function() {
	// 			sendPackage('data', {
	// 				name: 'data-' + i,
	// 				value: Math.floor(Math.random() * i)-2.5
	// 			});
	// 		}, 10);
	// 	})(i)
	// }
}
<|endoftext|>


<commit_before>var config = require("./config.js").get;
var _ = require('underscore');

// calculate the urlstub
var auth = "//" + config.cloudant.username + ":" + config.cloudant.password + "@";
var urlstub = config.cloudant.server.replace("//", auth) + ":" + config.cloudant.port;

// start up the nano driver
var nano = require('nano')(urlstub);

// connections to databases
var feeds = nano.db.use('feeds');
var articles = nano.db.use('articles');

// async library
var async = require('async');

// set http max connections
var http = require('http');
http.globalAgent.maxSockets = 25;

// set https max connections
var https = require('https');
https.globalAgent.maxSockets = 25;

// create the feeds database
var createFeeds = function (callback) {
  console.log("Checking feeds database");
  // create some databases
  nano.db.create('feeds', function (err, body) {
    if(!err || (err && !_.isUndefined(err.status_code) && err.status_code == 412)) {
      callback(null, body);
    } else {
      callback(err.reason, body);
    }
  });
};

// create the articles database
var createArticles = function (callback) {
  console.log("Checking articles database");
  // create some databases
  nano.db.create('articles', function (err, body) {
    if(!err || (err && !_.isUndefined(err.status_code) && err.status_code == 412)) {
      callback(null, body);
    } else {
      callback(err.reason, body);
    }
  });
};

// check to see if view "id" has contains "content"; if not replace it
var checkView = function (id, content, callback) {
  var rev = null;

  // fetch the view
  articles.get(id, function (err, data) {

    // if there's no existing data
    if (!data) {
      data = {};
      rev = null;
    } else {
      rev = data._rev;
      delete data._rev;
    }

    // if comparison  of stringified versions are different
    if (JSON.stringify(data) !== JSON.stringify(content)) {
      if (rev) {
        content._rev = rev;
      }

      // update the saved version
      articles.insert(content, function (err, data) {
        callback(null, true);
      });
    } else {
      callback(null, false);
    }

  });
};

// create any required views
var createViews = function (callback) {

  var views = [],
	  i = 0,
	  v = {};

  // load the views from file
  views = require("./views.json");

  console.log("Checking views");
  for (i = 0; i < views.length; i++) {
    v = views[i];
    checkView(views[i]._id, views[i], function (err, data) {
    });
  }
  callback();
};

// compact the databases
var compact = function (callback) {

  nano.db.compact("feeds", function (err, data) {
  });

  nano.db.compact("articles", function (err, data) {
  });
  callback(null, {});

};

// create some databases and their views
var create = function (cb) {
  async.series([createFeeds, createArticles, createViews], function(err, results) {
    cb(err, null);
  });
};

module.exports = {
  feeds: feeds,
  articles: articles,
  createViews: createViews,
  compact: compact,
  create: create
};<commit_msg>forgot I did not have underscore<commit_after>var config = require("./config.js").get;
var _ = require('underscore');

// calculate the urlstub
var auth = "//" + config.cloudant.username + ":" + config.cloudant.password + "@";
var urlstub = config.cloudant.server.replace("//", auth) + ":" + config.cloudant.port;

// start up the nano driver
var nano = require('nano')(urlstub);

// connections to databases
var feeds = nano.db.use('feeds');
var articles = nano.db.use('articles');

// async library
var async = require('async');

// set http max connections
var http = require('http');
http.globalAgent.maxSockets = 25;

// set https max connections
var https = require('https');
https.globalAgent.maxSockets = 25;

// create the feeds database
var createFeeds = function (callback) {
  console.log("Checking feeds database");
  // create some databases
  nano.db.create('feeds', function (err, body) {
    if(!err || (err && typeof(err.status_code) !='undefined' && err.status_code == 412)) {
      callback(null, body);
    } else {
      callback(err.reason, body);
    }
  });
};

// create the articles database
var createArticles = function (callback) {
  console.log("Checking articles database");
  // create some databases
  nano.db.create('articles', function (err, body) {
    if(!err || (err && !_.isUndefined(err.status_code) && err.status_code == 412)) {
      callback(null, body);
    } else {
      callback(err.reason, body);
    }
  });
};

// check to see if view "id" has contains "content"; if not replace it
var checkView = function (id, content, callback) {
  var rev = null;

  // fetch the view
  articles.get(id, function (err, data) {

    // if there's no existing data
    if (!data) {
      data = {};
      rev = null;
    } else {
      rev = data._rev;
      delete data._rev;
    }

    // if comparison  of stringified versions are different
    if (JSON.stringify(data) !== JSON.stringify(content)) {
      if (rev) {
        content._rev = rev;
      }

      // update the saved version
      articles.insert(content, function (err, data) {
        callback(null, true);
      });
    } else {
      callback(null, false);
    }

  });
};

// create any required views
var createViews = function (callback) {

  var views = [],
	  i = 0,
	  v = {};

  // load the views from file
  views = require("./views.json");

  console.log("Checking views");
  for (i = 0; i < views.length; i++) {
    v = views[i];
    checkView(views[i]._id, views[i], function (err, data) {
    });
  }
  callback();
};

// compact the databases
var compact = function (callback) {

  nano.db.compact("feeds", function (err, data) {
  });

  nano.db.compact("articles", function (err, data) {
  });
  callback(null, {});

};

// create some databases and their views
var create = function (cb) {
  async.series([createFeeds, createArticles, createViews], function(err, results) {
    cb(err, null);
  });
};

module.exports = {
  feeds: feeds,
  articles: articles,
  createViews: createViews,
  compact: compact,
  create: create
};<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

// Database
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/jatrailmap');

var main =   require('./routes/main');
var trails =   require('./routes/trails');
var users =   require('./routes/users');

var geo = require('./geo');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// set size limit for received data, doesn't work
// app.use(bodyParser.json({limit: '50mb'}));
// app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));

app.use(function(req, res, next) {
    console.log("--------------------------------------------");
    console.log("url: ", req.url);
    console.log("cookies: ", req.cookies);
    console.log("query: ", req.query);
    console.log("body: ", req.body);
    req.db = db;
    req.geo = geo;
    next();
});

app.use('/', main);
app.use('/', trails);
app.use('/', users);

// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;
<commit_msg>Added a date to the log.<commit_after>var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

// Database
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/jatrailmap');

var main =   require('./routes/main');
var trails =   require('./routes/trails');
var users =   require('./routes/users');

var geo = require('./geo');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// set size limit for received data, doesn't work
// app.use(bodyParser.json({limit: '50mb'}));
// app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));

app.use(function(req, res, next) {
    console.log("--------------------------------------------");
    console.log((new Date()).toString());
    console.log("url: ", req.url);
    console.log("cookies: ", req.cookies);
    console.log("query: ", req.query);
    console.log("body: ", req.body);
    req.db = db;
    req.geo = geo;
    next();
});

app.use('/', main);
app.use('/', trails);
app.use('/', users);

// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;
<|endoftext|>


<commit_before>//*****************************************************************************
// Copyright (c) 2015 Auto-ID Lab. Japan
//
// Contributors:
//  Iori MIZUTANI (iori.mizutani@gmail.com)
//*****************************************************************************
// Make Intel Edison's BLE module for connecting a Texas Instruments SenstorTag CC2451
var async = require("async"), fs = require("fs"), getmac = require("getmac"), mqtt = require("mqtt"), nconf = require("nconf"), SensorTag = require("sensortag"), spawn = require("child_process").spawn;

// constants
var configFile = "/var/local/config.json";

var pidFile = "/var/local/iot.pid";

var mosquittoHost = "test.mosquitto.org";

var mosquittoPort = 1883;

var defaultTopic = "gif-iot";

var defaultInterval = 1e3;

// globals
var mqttHost, mqttPort, mqttTopic, mqttInterbal, sensorInterval;

// mqttClient
var mqttClient = null;

// tagData object
var tagData = {};

tagData.payload = {};

tagData.payload.deviceMac = null;

tagData.payload.sensorMac = undefined;

tagData.toJson = function() {
    return JSON.stringify(this.payload);
};

tagData.toBluemixJson = function() {
    return JSON.stringify({
        d: {
            myName: undefined,
            objectTemp: this.payload.objectTemp,
            ambientTemp: this.payload.ambientTemp,
            accelX: this.payload.accelX,
            accelY: this.payload.accelY,
            accelZ: this.payload.accelZ,
            humidity: this.payload.humidity,
            temp: this.payload.temp,
            magX: this.payload.magX,
            magY: this.payload.magY,
            magZ: this.payload.magZ,
            pressure: this.payload.pressure,
            gyroX: this.payload.gyroX,
            gyroY: this.payload.gyroY,
            gyroZ: this.payload.gyroZ,
            latitude: 35.621465,
            longitude: 139.748531
        }
    });
};

tagData.publish = function(sensorMac) {
    if (bluemix) {
        bluemixClient.publish("iot-2/evt/sample/fmt/json", tagData.toBluemixJson());
        console.log(tagData.toBluemixJson());
    } else {
        mqttClient.publish(mqttTopic + "/data/" + sensorMac, tagData.toJson());
    }
};

// mac address to discover
var macToDiscover = undefined;

// pending notifier pid
var pendingNotifier = null;

// bluemixOption
var bluemix = false;

// bluemixClient
var bluemixClient = null;

// read the config file
function readConfig() {
    nconf.argv().file({
        file: configFile
    });
    if (nconf.get("bluemix")) bluemix = true;
    mqttHost = nconf.get("mqtt:host") || mosquittoHost;
    mqttPort = nconf.get("mqtt:port") || mosquittoPort;
    mqttTopic = nconf.get("mqtt:topic") || defaultTopic;
    mqttInterval = nconf.get("mqtt:interval") || defaultInterval;
    sensorInterval = nconf.get("sensor:interval") || mqttInterval;
    if (!tagData.payload.sensorMac && nconf.get("sensor:mac")) {
        tagData.payload.sensorMac = nconf.get("sensor:mac");
    }
    if (tagData.payload.sensorMac) {
        macToDiscover = tagData.payload.sensorMac.replace(/:/g, "").toLowerCase();
    }
    console.log("Press the side button on the SensorTag (" + tagData.payload.sensorMac + ") to connect");
}

// save the config to disk
function saveConfig() {
    nconf.set("mqtt:host", mqttHost);
    nconf.set("mqtt:port", mqttPort);
    nconf.set("mqtt:topic", mqttTopic);
    nconf.set("mqtt:interval", mqttInterval);
    nconf.set("sensor:interval", sensorInterval);
    nconf.set("sensor:mac", tagData.payload.sensorMac.toUpperCase().replace(/(.)(?=(..)+$)/g, "$1:"));
    nconf.save(function(err) {
        fs.readFile(configFile, function(err, data) {
            console.dir(JSON.parse(data.toString()));
        });
        fs.writeFile("/var/local/SENSOR_TAG", nconf.get("sensor:mac"), function(err) {
            if (err) console.log(err);
        });
    });
}

// called on message received
function doCommand(topic, message, packet) {
    console.log("received command: " + topic + " msg: " + message);
    var topics = topic.split("/");
    switch (topics[3]) {
      case "ping":
        var payload = JSON.parse(message);
        break;

      default:
        console.log("Unxpected Command: " + topics[3]);
    }
}

// cycle thru obx1 led color
function toggleRainbowLED() {
    spawn("bash", [ "/var/local/rainbow.sh" ], {
        stdio: "ignore",
        detached: true
    }).unref();
}

// write PID to file
function savePID() {
    fs.writeFile(pidFile, process.pid, function(err) {
        if (err) console.log(err);
    });
}

// graceful shutdown
function gracefulShutdown() {
    // delete PID file
    fs.unlink(pidFile, function(err) {
        if (err) throw err;
    });
    // reset LED
    toggleRainbowLED();
    if (mqttClient) {
        var ipmac = JSON.stringify({
            ip: nconf.get("ip"),
            sensorMac: nconf.get("sensor:mac"),
            deviceMac: tagData.payload.deviceMac,
            nodeStatus: "down"
        });
        mqttClient.publish("gif-iot/ip", ipmac);
        console.log("*** [gif-iot/ip] " + ipmac);
        mqttClient.end();
    }
    if (bluemixClient) bluemixClient.end();
    process.exit(0);
}

//*****************************************************************************
/* node */
//*****************************************************************************
process.on("exit", function(code) {
    console.log("*** Exiting with code: " + code);
});

var signals = [ "SIGINT", "SIGTERM", "SIGQUIT" ];

for (i in signals) {
    process.on(signals[i], function() {
        console.log("\n" + signals[i]);
        gracefulShutdown();
    });
}

async.series([ function(callback) {
    fs.readFile("/var/local/SENSOR_TAG", "utf8", function(err, data) {
        // if (err) throw err; // just skip if file not found
        tagData.payload.sensorMac = data;
    });
    callback();
}, function(callback) {
    readConfig();
    callback();
}, function(callback) {
    // get device mac address
    getmac.getMac(function(err, mac) {
        if (err) throw err;
        tagData.payload.deviceMac = mac.toUpperCase();
    });
    callback();
}, function(callback) {
    // create MQTT client
    console.log("*** [MQTT] Connect to the mqtt broker: " + mqttHost);
    if (bluemix) {
        bluemixClient = mqtt.connect({
            port: "1883",
            host: "quickstart.messaging.internetofthings.ibmcloud.com",
            keepalive: 30,
            clientId: "d:quickstart:iotsample-ti-bbst:" + macToDiscover
        });
    } else {
        mqttClient = mqtt.connect({
            port: mqttPort,
            host: mqttHost,
            keepalive: 30
        });
    }
    callback();
}, function(callback) {
    if (nconf.get("ip") != undefined) {
        pendingNotifier = setInterval(function(tag) {
            var ipmac = JSON.stringify({
                ip: nconf.get("ip"),
                sensorMac: nconf.get("sensor:mac"),
                deviceMac: tagData.payload.deviceMac,
                nodeStatus: "pending"
            });
            if (!bluemix) mqttClient.publish("gif-iot/ip", ipmac);
            console.log("*** [gif-iot/ip] " + ipmac);
        }, 1e3);
    }
    callback();
}, function(callback) {
    toggleRainbowLED();
    callback();
} ]);

SensorTag.discover(function(sensorTag) {
    sensorTag.on("disconnect", function() {
        console.log("*** SensorTag disconnected");
        gracefulShutdown();
    });
    // asynchronous functions in series
    async.series([ function(callback) {
        // save pid
        savePID();
        if (pendingNotifier) clearInterval(pendingNotifier);
        callback();
    }, function(callback) {
        // stop rainbowLED
        toggleRainbowLED();
        callback();
    }, function(callback) {
        // connect to the sensor tag
        console.log("*** [SensorTag] connect");
        sensorTag.connect(callback);
    }, function(callback) {
        // discover services and characteristics
        console.log("*** [SensorTag] discover services and characteristics");
        sensorTag.discoverServicesAndCharacteristics(callback);
    }, function(callback) {
        // get and save MAC address of the sensor tag
        console.log("*** [SensorTag] get MAC address");
        tagData.payload.sensorMac = sensorTag.uuid;
        callback();
    }, function(callback) {
        // save config with new MAC address
        saveConfig();
        if (nconf.get("ip") != undefined) {
            // get device mac address
            var ipmac = JSON.stringify({
                ip: nconf.get("ip"),
                sensorMac: nconf.get("sensor:mac"),
                deviceMac: tagData.payload.deviceMac
            });
            if (!bluemix) mqttClient.publish("gif-iot/ip", ipmac);
            console.log("*** [gif-iot/ip] " + ipmac);
        } else {
            console.log("*** [Option] IP address not provided");
        }
        callback();
    }, function(callback) {
        // irTemperature
        console.log("*** [SensorTag] Enabling irTemperature");
        sensorTag.enableIrTemperature(callback);
    }, function(callback) {
        sensorTag.on("irTemperatureChange", function(objectTemperature, ambientTemperature) {
            tagData.payload.objectTemp = parseFloat(objectTemperature.toFixed(1));
            tagData.payload.ambientTemp = parseFloat(ambientTemperature.toFixed(1));
        });
        sensorTag.notifyIrTemperature(callback);
    }, function(callback) {
        // accelerometer
        console.log("*** [SensorTag] Enabling accelerometer");
        sensorTag.enableAccelerometer(callback);
    }, function(callback) {
        sensorTag.setAccelerometerPeriod(sensorInterval, callback);
    }, function(callback) {
        sensorTag.on("accelerometerChange", function(x, y, z) {
            tagData.payload.accelX = parseFloat(x.toFixed(4));
            tagData.payload.accelY = parseFloat(y.toFixed(4));
            tagData.payload.accelZ = parseFloat(z.toFixed(4));
        });
        sensorTag.notifyAccelerometer(callback);
    }, function(callback) {
        // humidity
        console.log("*** [SensorTag] Enabling humidity");
        sensorTag.enableHumidity(callback);
    }, function(callback) {
        sensorTag.on("humidityChange", function(temperature, humidity) {
            tagData.payload.humidity = parseFloat(humidity.toFixed(1));
            tagData.payload.temp = parseFloat(temperature.toFixed(1));
        });
        sensorTag.notifyHumidity(callback);
    }, function(callback) {
        // magnetometer
        console.log("*** [SensorTag] Enabling magnetometer");
        sensorTag.enableMagnetometer(callback);
    }, function(callback) {
        sensorTag.setMagnetometerPeriod(sensorInterval, callback);
    }, function(callback) {
        sensorTag.on("magnetometerChange", function(x, y, z) {
            tagData.payload.magX = parseFloat(x.toFixed(1));
            tagData.payload.magY = parseFloat(y.toFixed(1));
            tagData.payload.magZ = parseFloat(z.toFixed(1));
        });
        sensorTag.notifyMagnetometer(callback);
    }, function(callback) {
        // barometricPressure
        console.log("*** [SensorTag] Enabling barometricPressure");
        sensorTag.enableBarometricPressure(callback);
    }, function(callback) {
        sensorTag.on("barometricPressureChange", function(pressure) {
            tagData.payload.pressure = parseFloat(pressure.toFixed(1));
        });
        sensorTag.notifyBarometricPressure(callback);
    }, function(callback) {
        // gyroscope
        console.log("*** [SensorTag] Enabling gyroscope");
        sensorTag.enableGyroscope(callback);
    }, function(callback) {
        sensorTag.on("gyroscopeChange", function(x, y, z) {
            tagData.payload.gyroX = parseFloat(x.toFixed(1));
            tagData.payload.gyroY = parseFloat(y.toFixed(1));
            tagData.payload.gyroZ = parseFloat(z.toFixed(1));
        });
        sensorTag.notifyGyroscope(callback);
    }, function(callback) {
        // simleKey
        sensorTag.on("simpleKeyChange", function(left, right) {
            tagData.payload.left = left;
            tagData.payload.right = right;
        });
        sensorTag.notifySimpleKey(callback);
    }, function(callback) {
        // MQTT subscribe to cmd topic
        if (!bluemix) {
            console.log("*** [MQTT] Subscribe to " + mqttTopic + "/cmd/" + nconf.get("sensor:mac"));
            mqttClient.subscribe(mqttTopic + "/cmd/" + nconf.get("sensor:mac"));
            mqttClient.on("message", doCommand);
        }
        callback();
    }, function(callback) {
        // MQTT publish sensor data
        console.log("*** [MQTT] Publish to " + mqttTopic + "/data/" + nconf.get("sensor:mac"));
        setInterval(function(tag) {
            tag.publish(nconf.get("sensor:mac"));
        }, mqttInterval, tagData);
    }, function(callback) {
        // disconnect from the sensor tag
        sensorTag.disconnect(callback);
    } ]);
}, macToDiscover);
<commit_msg>bluemix optionize<commit_after>//*****************************************************************************
// Copyright (c) 2015 Auto-ID Lab. Japan
//
// Contributors:
//  Iori MIZUTANI (iori.mizutani@gmail.com)
//*****************************************************************************
// Make Intel Edison's BLE module for connecting a Texas Instruments SenstorTag CC2451
var async = require("async"), fs = require("fs"), getmac = require("getmac"), mqtt = require("mqtt"), nconf = require("nconf"), SensorTag = require("sensortag"), spawn = require("child_process").spawn;

// constants
var configFile = "/var/local/config.json";

var pidFile = "/var/local/iot.pid";

var mosquittoHost = "test.mosquitto.org";

var mosquittoPort = 1883;

var defaultTopic = "gif-iot";

var defaultInterval = 1e3;

// globals
var mqttHost, mqttPort, mqttTopic, mqttInterbal, sensorInterval;

// mqttClient
var mqttClient = null;

// tagData object
var tagData = {};

tagData.payload = {};

tagData.payload.deviceMac = null;

tagData.payload.sensorMac = undefined;

tagData.toJson = function() {
    return JSON.stringify(this.payload);
};

tagData.toBluemixJson = function() {
    return JSON.stringify({
        d: {
            myName: undefined,
            objectTemp: this.payload.objectTemp,
            ambientTemp: this.payload.ambientTemp,
            accelX: this.payload.accelX,
            accelY: this.payload.accelY,
            accelZ: this.payload.accelZ,
            humidity: this.payload.humidity,
            temp: this.payload.temp,
            magX: this.payload.magX,
            magY: this.payload.magY,
            magZ: this.payload.magZ,
            pressure: this.payload.pressure,
            gyroX: this.payload.gyroX,
            gyroY: this.payload.gyroY,
            gyroZ: this.payload.gyroZ,
            latitude: 35.621465,
            longitude: 139.748531
        }
    });
};

tagData.publish = function(sensorMac) {
    mqttClient.publish(mqttTopic + "/data/" + sensorMac, tagData.toJson());
    if (bluemix) {
        bluemixClient.publish("iot-2/evt/sample/fmt/json", tagData.toBluemixJson());
        console.log(tagData.toBluemixJson());
    }
};

// mac address to discover
var macToDiscover = undefined;

// pending notifier pid
var pendingNotifier = null;

// bluemixOption
var bluemix = false;

// bluemixClient
var bluemixClient = null;

// read the config file
function readConfig() {
    nconf.argv().file({
        file: configFile
    });
    if (nconf.get("bluemix")) bluemix = true;
    mqttHost = nconf.get("mqtt:host") || mosquittoHost;
    mqttPort = nconf.get("mqtt:port") || mosquittoPort;
    mqttTopic = nconf.get("mqtt:topic") || defaultTopic;
    mqttInterval = nconf.get("mqtt:interval") || defaultInterval;
    sensorInterval = nconf.get("sensor:interval") || mqttInterval;
    if (!tagData.payload.sensorMac && nconf.get("sensor:mac")) {
        tagData.payload.sensorMac = nconf.get("sensor:mac");
    }
    if (tagData.payload.sensorMac) {
        macToDiscover = tagData.payload.sensorMac.replace(/:/g, "").toLowerCase();
    }
    console.log("Press the side button on the SensorTag (" + tagData.payload.sensorMac + ") to connect");
}

// save the config to disk
function saveConfig() {
    nconf.set("mqtt:host", mqttHost);
    nconf.set("mqtt:port", mqttPort);
    nconf.set("mqtt:topic", mqttTopic);
    nconf.set("mqtt:interval", mqttInterval);
    nconf.set("sensor:interval", sensorInterval);
    nconf.set("sensor:mac", tagData.payload.sensorMac.toUpperCase().replace(/(.)(?=(..)+$)/g, "$1:"));
    nconf.save(function(err) {
        fs.readFile(configFile, function(err, data) {
            console.dir(JSON.parse(data.toString()));
        });
        fs.writeFile("/var/local/SENSOR_TAG", nconf.get("sensor:mac"), function(err) {
            if (err) console.log(err);
        });
    });
}

// called on message received
function doCommand(topic, message, packet) {
    console.log("received command: " + topic + " msg: " + message);
    var topics = topic.split("/");
    switch (topics[3]) {
      case "ping":
        var payload = JSON.parse(message);
        break;

      default:
        console.log("Unxpected Command: " + topics[3]);
    }
}

// cycle thru obx1 led color
function toggleRainbowLED() {
    spawn("bash", [ "/var/local/rainbow.sh" ], {
        stdio: "ignore",
        detached: true
    }).unref();
}

// write PID to file
function savePID() {
    fs.writeFile(pidFile, process.pid, function(err) {
        if (err) console.log(err);
    });
}

// graceful shutdown
function gracefulShutdown() {
    // delete PID file
    fs.unlink(pidFile, function(err) {
        if (err) throw err;
    });
    // reset LED
    toggleRainbowLED();
    if (mqttClient) {
        var ipmac = JSON.stringify({
            ip: nconf.get("ip"),
            sensorMac: nconf.get("sensor:mac"),
            deviceMac: tagData.payload.deviceMac,
            nodeStatus: "down"
        });
        mqttClient.publish("gif-iot/ip", ipmac);
        console.log("*** [gif-iot/ip] " + ipmac);
        mqttClient.end();
    }
    if (bluemixClient) bluemixClient.end();
    process.exit(0);
}

//*****************************************************************************
/* node */
//*****************************************************************************
process.on("exit", function(code) {
    console.log("*** Exiting with code: " + code);
});

var signals = [ "SIGINT", "SIGTERM", "SIGQUIT" ];

for (i in signals) {
    process.on(signals[i], function() {
        console.log("\n" + signals[i]);
        gracefulShutdown();
    });
}

async.series([ function(callback) {
    fs.readFile("/var/local/SENSOR_TAG", "utf8", function(err, data) {
        // if (err) throw err; // just skip if file not found
        tagData.payload.sensorMac = data;
    });
    callback();
}, function(callback) {
    readConfig();
    callback();
}, function(callback) {
    // get device mac address
    getmac.getMac(function(err, mac) {
        if (err) throw err;
        tagData.payload.deviceMac = mac.toUpperCase();
    });
    callback();
}, function(callback) {
    // create MQTT client
    console.log("*** [MQTT] Connect to the mqtt broker: " + mqttHost);
    mqttClient = mqtt.connect({
        port: mqttPort,
        host: mqttHost,
        keepalive: 30
    });
    if (bluemix) {
        bluemixClient = mqtt.connect({
            port: "1883",
            host: "quickstart.messaging.internetofthings.ibmcloud.com",
            keepalive: 30,
            clientId: "d:quickstart:iotsample-ti-bbst:" + macToDiscover
        });
    }
    callback();
}, function(callback) {
    if (nconf.get("ip") != undefined) {
        pendingNotifier = setInterval(function(tag) {
            var ipmac = JSON.stringify({
                ip: nconf.get("ip"),
                sensorMac: nconf.get("sensor:mac"),
                deviceMac: tagData.payload.deviceMac,
                nodeStatus: "pending"
            });
            mqttClient.publish("gif-iot/ip", ipmac);
            console.log("*** [gif-iot/ip] " + ipmac);
        }, 1e3);
    }
    callback();
}, function(callback) {
    toggleRainbowLED();
    callback();
} ]);

SensorTag.discover(function(sensorTag) {
    sensorTag.on("disconnect", function() {
        console.log("*** SensorTag disconnected");
        gracefulShutdown();
    });
    // asynchronous functions in series
    async.series([ function(callback) {
        // save pid
        savePID();
        if (pendingNotifier) clearInterval(pendingNotifier);
        callback();
    }, function(callback) {
        // stop rainbowLED
        toggleRainbowLED();
        callback();
    }, function(callback) {
        // connect to the sensor tag
        console.log("*** [SensorTag] connect");
        sensorTag.connect(callback);
    }, function(callback) {
        // discover services and characteristics
        console.log("*** [SensorTag] discover services and characteristics");
        sensorTag.discoverServicesAndCharacteristics(callback);
    }, function(callback) {
        // get and save MAC address of the sensor tag
        console.log("*** [SensorTag] get MAC address");
        tagData.payload.sensorMac = sensorTag.uuid;
        callback();
    }, function(callback) {
        // save config with new MAC address
        saveConfig();
        if (nconf.get("ip") != undefined) {
            // get device mac address
            var ipmac = JSON.stringify({
                ip: nconf.get("ip"),
                sensorMac: nconf.get("sensor:mac"),
                deviceMac: tagData.payload.deviceMac
            });
            mqttClient.publish("gif-iot/ip", ipmac);
            console.log("*** [gif-iot/ip] " + ipmac);
        } else {
            console.log("*** [Option] IP address not provided");
        }
        callback();
    }, function(callback) {
        // irTemperature
        console.log("*** [SensorTag] Enabling irTemperature");
        sensorTag.enableIrTemperature(callback);
    }, function(callback) {
        sensorTag.on("irTemperatureChange", function(objectTemperature, ambientTemperature) {
            tagData.payload.objectTemp = parseFloat(objectTemperature.toFixed(1));
            tagData.payload.ambientTemp = parseFloat(ambientTemperature.toFixed(1));
        });
        sensorTag.notifyIrTemperature(callback);
    }, function(callback) {
        // accelerometer
        console.log("*** [SensorTag] Enabling accelerometer");
        sensorTag.enableAccelerometer(callback);
    }, function(callback) {
        sensorTag.setAccelerometerPeriod(sensorInterval, callback);
    }, function(callback) {
        sensorTag.on("accelerometerChange", function(x, y, z) {
            tagData.payload.accelX = parseFloat(x.toFixed(4));
            tagData.payload.accelY = parseFloat(y.toFixed(4));
            tagData.payload.accelZ = parseFloat(z.toFixed(4));
        });
        sensorTag.notifyAccelerometer(callback);
    }, function(callback) {
        // humidity
        console.log("*** [SensorTag] Enabling humidity");
        sensorTag.enableHumidity(callback);
    }, function(callback) {
        sensorTag.on("humidityChange", function(temperature, humidity) {
            tagData.payload.humidity = parseFloat(humidity.toFixed(1));
            tagData.payload.temp = parseFloat(temperature.toFixed(1));
        });
        sensorTag.notifyHumidity(callback);
    }, function(callback) {
        // magnetometer
        console.log("*** [SensorTag] Enabling magnetometer");
        sensorTag.enableMagnetometer(callback);
    }, function(callback) {
        sensorTag.setMagnetometerPeriod(sensorInterval, callback);
    }, function(callback) {
        sensorTag.on("magnetometerChange", function(x, y, z) {
            tagData.payload.magX = parseFloat(x.toFixed(1));
            tagData.payload.magY = parseFloat(y.toFixed(1));
            tagData.payload.magZ = parseFloat(z.toFixed(1));
        });
        sensorTag.notifyMagnetometer(callback);
    }, function(callback) {
        // barometricPressure
        console.log("*** [SensorTag] Enabling barometricPressure");
        sensorTag.enableBarometricPressure(callback);
    }, function(callback) {
        sensorTag.on("barometricPressureChange", function(pressure) {
            tagData.payload.pressure = parseFloat(pressure.toFixed(1));
        });
        sensorTag.notifyBarometricPressure(callback);
    }, function(callback) {
        // gyroscope
        console.log("*** [SensorTag] Enabling gyroscope");
        sensorTag.enableGyroscope(callback);
    }, function(callback) {
        sensorTag.on("gyroscopeChange", function(x, y, z) {
            tagData.payload.gyroX = parseFloat(x.toFixed(1));
            tagData.payload.gyroY = parseFloat(y.toFixed(1));
            tagData.payload.gyroZ = parseFloat(z.toFixed(1));
        });
        sensorTag.notifyGyroscope(callback);
    }, function(callback) {
        // simleKey
        sensorTag.on("simpleKeyChange", function(left, right) {
            tagData.payload.left = left;
            tagData.payload.right = right;
        });
        sensorTag.notifySimpleKey(callback);
    }, function(callback) {
        // MQTT subscribe to cmd topic
        console.log("*** [MQTT] Subscribe to " + mqttTopic + "/cmd/" + nconf.get("sensor:mac"));
        mqttClient.subscribe(mqttTopic + "/cmd/" + nconf.get("sensor:mac"));
        mqttClient.on("message", doCommand);
        callback();
    }, function(callback) {
        // MQTT publish sensor data
        console.log("*** [MQTT] Publish to " + mqttTopic + "/data/" + nconf.get("sensor:mac"));
        setInterval(function(tag) {
            tag.publish(nconf.get("sensor:mac"));
        }, mqttInterval, tagData);
    }, function(callback) {
        // disconnect from the sensor tag
        sensorTag.disconnect(callback);
    } ]);
}, macToDiscover);
<|endoftext|>


<commit_before>(function( $ ){

    var methods = {
        init : function(options) {

            var defaults = {
                img_path: 'nsProgress'
            };

            options = $.extend(defaults, options);
            height_without_text = 60;
            height_with_text = 80;

            $(this).addClass('nsProgress_container');
            $('body').append('

');

            $(this).append('
Loading…
');
        },
        show : function( ) {
            $(this).show();
        },
        showWithMaskType : function( type ) {

            switch(type) {
                case 'none':
                    break;
                case 'clear':
                    $('.nsProgress_block').show();
                    break;yep
                case 'black':
                    $('.nsProgress_block').show();
                    $('.nsProgress_block').css('background', 'rgba(0, 0, 0, 0.5)');
                    break;
                default:
                    break;
            }

            $(this).nsProgress('show');
        },
        showWithStatus : function( status ) {

            $(this).css('height', height_with_text + 'px');
            $(this).find('.nsProgress_text').html( status ).show();;
            $(this).nsProgress('show');

        },
        showWithStatusAndMaskType : function ( status, type ) {

            $(this).nsProgress('showWithMaskType', type);
            $(this).nsProgress('showWithStatus', status);

        },
        showWithImage : function( image_name ) {

            $(this).find('.nsProgress_img').attr('src', $(this).find('.nsProgress_img').attr('data-src') + '/' + image_name);
            $(this).nsProgress('show');

        },
        showSuccessWithStatus : function ( status ) {

            $(this).nsProgress('showWithImage', 'nsSuccess.png');
            $(this).nsProgress('showWithStatus', status);

        },
        showErrorWithStatus : function ( status ) {

            $(this).nsProgress('showWithImage', 'nsError.png');
            $(this).nsProgress('showWithStatus', status);

        },
        showSuccessWithStatusAndMaskType : function ( status, type ) {

            $(this).nsProgress('showWithImage', 'nsSuccess.png');
            $(this).nsProgress('showWithStatusAndMaskType', status, type);

        },
        showErrorWithStatusAndMaskType : function ( status, type ) {

            $(this).nsProgress('showWithImage', 'nsError.png');
            $(this).nsProgress('showWithStatusAndMaskType', status, type);

        },
        showWithImageAndStatus : function ( image, status ) {

            $(this).nsProgress('showWithImage', image);
            $(this).nsProgress('showWithStatus', status);

        },
        showWithImageAndStatusAndMaskType : function ( image, status, type ) {

            $(this).nsProgress('showWithImage', image);
            $(this).nsProgress('showWithStatusAndMaskType', status, type);

        },
        showWithImageAndMaskType : function ( image, type ) {

            $(this).nsProgress('showWithImage', image);
            $(this).nsProgress('showWithMaskType', type);

        },
        dismiss : function() {

            // Flush the styles out
            $('.nsProgress_block').attr('style', '');
            $(this).find('.nsProgress_text').attr('style', '').html('').hide();
            $(this).attr('style', '');

            $(this).find('.nsProgress_img').attr('src', $(this).find('.nsProgress_img').attr('data-src') + '/nsLoader.gif');

            $(this).hide();
            $('.nsProgress_block').hide();
        }
    };

    $.fn.nsProgress = function(methodOrOptions) {
        if ( methods[methodOrOptions] ) {
            return methods[ methodOrOptions ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) {
            // Default to "init"
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.nsProgress' );
        }
    };

})( jQuery );<commit_msg>Altered default path so that it reflects the plugin paths<commit_after>(function( $ ){

    var methods = {
        init : function(options) {

            var defaults = {
                img_path: 'nsProgress/img'
            };

            options = $.extend(defaults, options);
            height_without_text = 60;
            height_with_text = 80;

            $(this).addClass('nsProgress_container');
            $('body').append('

');

            $(this).append('
Loading…
');
        },
        show : function( ) {
            $(this).show();
        },
        showWithMaskType : function( type ) {

            switch(type) {
                case 'none':
                    break;
                case 'clear':
                    $('.nsProgress_block').show();
                    break;yep
                case 'black':
                    $('.nsProgress_block').show();
                    $('.nsProgress_block').css('background', 'rgba(0, 0, 0, 0.5)');
                    break;
                default:
                    break;
            }

            $(this).nsProgress('show');
        },
        showWithStatus : function( status ) {

            $(this).css('height', height_with_text + 'px');
            $(this).find('.nsProgress_text').html( status ).show();;
            $(this).nsProgress('show');

        },
        showWithStatusAndMaskType : function ( status, type ) {

            $(this).nsProgress('showWithMaskType', type);
            $(this).nsProgress('showWithStatus', status);

        },
        showWithImage : function( image_name ) {

            $(this).find('.nsProgress_img').attr('src', $(this).find('.nsProgress_img').attr('data-src') + '/' + image_name);
            $(this).nsProgress('show');

        },
        showSuccessWithStatus : function ( status ) {

            $(this).nsProgress('showWithImage', 'nsSuccess.png');
            $(this).nsProgress('showWithStatus', status);

        },
        showErrorWithStatus : function ( status ) {

            $(this).nsProgress('showWithImage', 'nsError.png');
            $(this).nsProgress('showWithStatus', status);

        },
        showSuccessWithStatusAndMaskType : function ( status, type ) {

            $(this).nsProgress('showWithImage', 'nsSuccess.png');
            $(this).nsProgress('showWithStatusAndMaskType', status, type);

        },
        showErrorWithStatusAndMaskType : function ( status, type ) {

            $(this).nsProgress('showWithImage', 'nsError.png');
            $(this).nsProgress('showWithStatusAndMaskType', status, type);

        },
        showWithImageAndStatus : function ( image, status ) {

            $(this).nsProgress('showWithImage', image);
            $(this).nsProgress('showWithStatus', status);

        },
        showWithImageAndStatusAndMaskType : function ( image, status, type ) {

            $(this).nsProgress('showWithImage', image);
            $(this).nsProgress('showWithStatusAndMaskType', status, type);

        },
        showWithImageAndMaskType : function ( image, type ) {

            $(this).nsProgress('showWithImage', image);
            $(this).nsProgress('showWithMaskType', type);

        },
        dismiss : function() {

            // Flush the styles out
            $('.nsProgress_block').attr('style', '');
            $(this).find('.nsProgress_text').attr('style', '').html('').hide();
            $(this).attr('style', '');

            $(this).find('.nsProgress_img').attr('src', $(this).find('.nsProgress_img').attr('data-src') + '/nsLoader.gif');

            $(this).hide();
            $('.nsProgress_block').hide();
        }
    };

    $.fn.nsProgress = function(methodOrOptions) {
        if ( methods[methodOrOptions] ) {
            return methods[ methodOrOptions ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) {
            // Default to "init"
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.nsProgress' );
        }
    };

})( jQuery );<|endoftext|>