'use strict'; 

//
//mqtt
var mqtt = require('mqtt');
var opt = {
  port:1883,
  clientId: 'phonetest'
};

var client  = mqtt.connect('tcp://iot.twgigatech.cn:1883');
client.on('connect', function () 
{
console.log('connect MQTT server');
client.subscribe("CAD9A3D3EUWWNBKY111A/iotk");
client.subscribe("CAD9A3D3EUWWNBKY111A/phone");
// client.publish('CAD9A3D3EUWWNBKY/iotk','test');

});

client.on('message', function (topic, message) {
  console.log('mqtt rece: '+message.toString());
//wsConnect.send(message);
//  client.end();
});


//

var fs = require('fs'); 

var cfg = { 
ssl: true, 
port: 443, 
ssl_key: 'ssl.key', ssl_cert: 'ssl.crt' 
}; 

var httpServ = (cfg.ssl) ? require('https') : require('http');
 var WebSocketServer = require('ws').Server;
 var app = null; 

 var processRequest = function(req, res)
 { 
res.writeHead(200);
 res.end('All glory to WebSockets!\n');
 }; 

if (cfg.ssl) {
 app = httpServ.createServer({ 
 key: fs.readFileSync(cfg.ssl_key),
 cert: fs.readFileSync(cfg.ssl_cert) 
}, processRequest).listen(cfg.port); 
} else {
 app = httpServ.createServer(processRequest).listen(cfg.port);
 } 

 var wss = new WebSocketServer({ server: app });
 wss.on('connection', function(wsConnect)
 {


 wsConnect.on('message', function(message)
 { 
	console.log('wss rece: '+message); 
        client.publish('CAD9A3D3EUWWNBKY/iotk',message.toString());
	//wsConnect.send(message);
 }); 
});


