<repo_name>eakl/sgs<file_sep>/README.md
# sgs


### Objectives

- **Keep plants at an optimal soil moisture level:** An intelligent algorithm takes care of deciding when it is appropriate to water the plants.
- **Obtain data from a local network of sensors:** A local network of sensors acquires useful data such as temperature, humidity, soil moisture, water level, rainfall, and light exposure from the plants and transmits it to the central controller (Arduino)
- **Control a water delivery system in an unobtrusive way:** The controller manages a new or existing watering system by controlling either a pump or a solenoid.
- **Obtain up-to-date weather forecasts for the current location of the device:** By using an available internet connection to parse data from an open source weather website.
- **Implement a zero-configuration environment:** By employing self-learning algorithms the system is able to optimally configure itself to the setup in which is installed.
- **Respond to external events (e.g. the plants have been watered by the user):** By intelligently using the sensors the system can detect if external events require modification to its plan of action.
- **Compensate possible hardware failures:** If the network sensor is degraded the system will resort to a fail-safe configuration. Furthermore, using carefully designed circuitry and software, reliable operation of the water delivery system is ensured.
- **Present the data gathered to the user in an intuitive way:** By means of a locally available webserver acting as a gateway between the user and the controller software.
- **Allow manual control of the watering system:** The option to manually override the system is available to the user, should the need arise.
- **Offer the possibility of fine-tuning the system, especially for advanced users:** The compromises required by the autoconfiguration can be removed if the user is willing to provide additional feedback to the system.
- **Be easily extensible: sensors should be easily added to a pre-existing network:** Flexibility is always important. The sensor network is designed so that the user can, when desired, extend it.




http://ami-2014.github.io/NULL/details.html
<file_sep>/quick-dirty/config.js
'use strict'

const config = {
  mqtt: {
    uri: 'mqtt://test.mosquitto.org',
    port: 3000,
    options: {
      clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
      clean: true, // set to false to receive QoS 1 and 2 messages while offline
      keepalive: 60, // seconds, set to 0 to disable
      reconnectPeriod: 1000, // milliseconds, interval between two reconnections
      connectTimeout: 30 * 1000, // milliseconds, time to wait before a CONNACK is received
      username: 'elias',
      password: '<PASSWORD>',
      will: {
        topic: '',
        payload: '',
        qos: 2,
        retain: 1
      }
    }
  }
}

module.exports = {
  config
}
<file_sep>/quick-dirty/dbSchema.js
'use strict'






const fact_temperature = {
  _id: 1,
  sensorId: c2347df,
  timestamp: '0000-00-00 00:00:00',
  value: 23
}

const dim_customer = {
  _id: 1,
  customerId: b3259874,
  customerType: 'business',
  _name: 'elly',
  contact: 'email',
  country: 'fr',
  city: 'paris',
  long: 1.255688,
  lat: 1.479423
}

const dim_device
- id
- model



dim_plant
- id
- care_information
- age


dim_sensor
- id
- device_id
- position



fact_subscription


fact_temperature
- id
- sensorId
- ts
- value

fact_humidity
- id
- sensorId
- ts
- value
<file_sep>/quick-dirty/server.js
'use strict'

const Mqtt = require('mqtt')
const { config } = require('./config')

// Launch the server
const client = Mqtt.connect(config.mqtt.uri) // , config['mqtt']['options']

client.on('connect', (connack) => {
  if (connack.returnCode == 0) {
    console.log('Server Connection Accepted')
  }

  client.subscribe('temperature')
})



client.on('message', (topic, message) => {
  const temp = {temp: parseInt(JSON.parse(message).temp, 10)}
  console.log(temp)
})
<file_sep>/config/index.js
'use strict'

const Yaml = require('js-yaml')
const Fs = require('fs')

try {
  const conf = Yaml.safeLoad(Fs.readFileSync(__dirname + '/conf.yml', 'utf8'))
  const indentedJson = JSON.stringify(conf, null, 4)
  console.log(indentedJson)
} catch (err) {
  console.log(err)
}

// module.exports = {
//   conf
// }
<file_sep>/lib/subscriber.js
'use strict'

const Mqtt = require('Mqtt')
const client = Mqtt.connect('mqtt://test.mosquitto.org')

client.on('connect', () => {
  client.subscribe('sensor')
})

client.on('message', (topic, message) => {
  console.log(message.toString())
})
<file_sep>/green/data.js
'use strict'

const green = {
  isOk: true,
  age: 8,
  moisture:,
  humidity:,
  temperature:,
  water:,
  sunshine:,
  atmosphericPressure:
}
<file_sep>/lib/mqtt.js
'use strict'

// Refers to client instance in the config object to use the client accros all file
// with const mqttClient = require('../config').mqtt

const Mqtt = require('mqtt')
const config = require('../config/index.json')

const client  = Mqtt.connect(config['uri'], config['options'])

async function mqttConnect () {
  if (config.mqtt.instance) {
    return congif.mqtt.instance
  } else {
    try {
      console.log(`Connection to ${config.mqtt.uri} on port ${config.mqtt.port}`)
      config.mqtt.instance = Mqtt.connect(config.mqtt.uri, config.mqtt.options)
      console.log(`Connected to ${config.mqtt.instance} on port ${config.mqtt.port}`)
      return config.mqtt.instance
    } catch (err) {
      throw new Error (err)
    }
  }
}

// Recurring task should be an async function?
function pub(topic, message, every) {
  if (config.mqtt.instance) {
    if (every) {
      client.publish(topic, message)
    } else {
      client.publish(topic, message) // do something with a recurring delay - not setInterval
    }
  } else {
    // Recursive pub function?
    // Function to be fixed
    await mqttConnect().then(() => pub(topic, message, every))
  }
}

// async function connect (dbName) {
//   if (config[dbName].db) {
//     return config[dbName].db
//   } else {
//     try {
//       const url = `mongodb://${config[dbName].host}:${config[dbName].port}/${config[dbName].name}`
//       console.log(`Connecting to ${url}`)
//       config[dbName].db = await MongoClient.connect(url, config[dbName].opts)
//       console.log(`Connected to MongoDB: ${config[dbName].db.s.databaseName}`)
//       return config[dbName].db
//     } catch (err) {
//       throw new Error(err)
//     }
//   }
// }
//
// function close (dbName) {
//   if (config[dbName].db) {
//     console.log(`Closing ${config[dbName].name} connection.`)
//     config[dbName].db.close()
//   }
// }

module.exports = {
  connect,
  pub,
  sub
}
<file_sep>/quick-dirty/index.js
'use strict'

const Mqtt = require('mqtt')
const { config } = require('./config')


/**
 * 1. Connect
 * 2. Check that the connection is fine.
 * 3.
 * 4.
 * 5.
 * 6. Reconnect if needed
 */





// Launch the server
const client = Mqtt.connect(config.mqtt.uri) // , config['mqtt']['options']

client.on('connect', (connack) => {
  if (connack.returnCode == 0) {
    console.log('Connection Accepted')
  }

  setInterval(() => {
    const payload = {temp: Math.random().toString(10).substr(2,2)}
    client.publish('temperature', JSON.stringify(payload))
  }, 100)
})


function sendSys () {}
function sendData () {}

// Subscribe
'ping'

// When the ping is received, a pong (with system data and sensor data must be sent back) --> If no ping is received, put the wall on survial mode (default)
client.on('message', (tpc, msg, pck) => {
  switch (msg.req) {
    case 'sys':
      sendSys(msg.id)
      break
    case 'data':
      sendData(msg.id)
      break
    default:
      handleDefault()
  }
})



// function subscribe () {
//   client.subscribe('topic', (err, granted) => {
//     granted.forEach(
//       console.log(`Successfully subscribed to ${}`)
//     )
//   })
// }










  // connack.sessionPresent // true
  // connack.returnCode // 0
  // 0: 'Connection accepted'
  // 1: 'Connection refused; unacceptable protocol version'
  // 2: 'Connection refused; identifier rejected'
  // 3: 'Connection refused; server unavailable'
  // 4: 'Connection refused; bad user name or password'
  // 5: 'Connection refused; not authorized'







// client.on('error', (err) => {
//   console.log('ERROR: ', err)
// })
//
// client.on('connect', (connack) => {
//   console.log(connack)
//   console.log('connected')
// })
//
//
// client.publish('topic', "{test1: true}", () => {
//   console.log('published:')
// })


// options.protocol
// options.host
// options.port
// options.hostname
// options.keepalive: 60
// options.clean: true
// options.clientId: 'mqttjs_8abdf304'
<file_sep>/quick-dirty/index_bak.js
'use strict'

const Mqtt = require('mqtt')
const config = require('./config.json')


// Launch the server
const client = Mqtt.connect(config['mqtt']['uri'], config['mqtt']['options'])




client.on('error', (err) => {
  console.log(err)
})

client.on('connect', (connack) => {
  console.log(connack)
})

client.on('reconnect', () => {})


client.on('message', (topic, message, packet) => {})

client.on('packetsend', (packet) => {})
client.on('packetreceive', (packet) => {})

client.on('close', () => {})
client.on('offline', () => {})
client.on('end', () => {})








client.publish('topic', 'message', opts, (err))

['topic1', 'topic2', 'topic3']
{'topic1': {qos: 0}, 'topic2': {qos: 1}}
client.subscribe('topic', opts, (err, granted))

['topic1', 'topic2', 'topic3']
client.unsubscribe('topic', opts, (err))

client.end(())

client.reconnect()

client.connected()


client.getLastMessageId()


client.reconnecting()



// Store

const store = Mqtt.store(opts) // {clean: bool}

store.put({messageId: 0, ...}, ())
store.createStream()
store.del({messageId: 0, ...}, ())
store.close(())




//
//
//
//
//
//
//
//
//
//
//
//
// async function mqttConnect () {
//   if (config.mqtt.instance) {
//     return congif.mqtt.instance
//   } else {
//     try {
//       console.log(`Connection to ${config.mqtt.uri} on port ${config.mqtt.port}`)
//       config.mqtt.instance = await Mqtt.connect(config.mqtt.uri, config.mqtt.options)
//       console.log(`Connected to ${config.mqtt.instance} on port ${config.mqtt.port}`)
//       return config.mqtt.instance
//     } catch (err) {
//       throw new Error (err)
//     }
//   }
// }
//
// // Recurring task should be an async function?
// function pub(topic, message, every) {
//   if (config.mqtt.instance) {
//     if (every) {
//       client.publish(topic, message)
//     } else {
//       client.publish(topic, message) // do something with a recurring delay - not setInterval
//     }
//   } else {
//     // Recursive pub function?
//     // Function to be fixed
//     await mqttConnect().then(() => pub(topic, message, every))
//   }
// }
//
// function sub(topic, message, every) {
//   if (config.mqtt.instance) {
//     if (every) {
//       client.publish(topic, message)
//     } else {
//       client.publish(topic, message) // do something with a recurring delay - not setInterval
//     }
//   } else {
//     // Recursive pub function?
//     // Function to be fixed
//     await mqttConnect().then(() => pub(topic, message, every))
//   }
// }
<file_sep>/index.js
'use strict'

const config = require('./cong.json')
const Mqtt = require('mqtt')
const client = Mqtt.connect('')
