wechat wss demo

app.js 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. /**
  2. * Created by tom on 2018/1/21.
  3. */
  4. 'use strict';
  5. const Fs = require('fs');
  6. const Https = require('https');
  7. const WebSocket = require('ws');
  8. const uuid = require('uuid');
  9. var http = require("http");
  10. var express = require("express");
  11. var request = require("request");
  12. const path = require('path');
  13. var cmd = require('node-cmd');
  14. var WXBizDataCrypt = require('./WXBizDataCrypt');
  15. const BERRY_PI = 'BERRY_PI';
  16. const LOGIN = 'Login';
  17. const FORMID = 'SendFormId';
  18. const ENCRYPT = 'EncryptedData';
  19. const wsclients = {};
  20. const wssclients = {};
  21. const WebSocketServer = WebSocket.Server;
  22. const ws = new WebSocketServer({
  23. port: 8089
  24. });
  25. var curcnt=1;
  26. const appId = 'wx4680f6d1dc629d22';
  27. const appSecret = 'cc6a16ee5545e887c94d238dfefefac0';
  28. var formid;
  29. var encryptedData;
  30. var iv;
  31. console.log("websocketServer Listen port : 8089");
  32. ws.on('connection', function (ws) {
  33. console.log(`[WS SERVER] connection()`);
  34. ws.clientId = uuid.v1();
  35. wsclients[ws.clientId] = ws;
  36. console.log('client connected:'+ws.clientId);
  37. ws.on('message', function (message) {
  38. console.log(`[WS SERVER] Received: ${message}`);
  39. ws.send(`ECHO: ${message}`, (err) => {
  40. if (err) {
  41. console.log(`[WS SERVER] error: ${err}`);
  42. }
  43. });
  44. });
  45. ws.on('close', () => {
  46. console.log(`[WS SERVER] close`);
  47. if(ws.clientId) {
  48. delete wsclients[ws.clientId];
  49. console.log('wsclient:'+ws.clientId);
  50. }
  51. });
  52. });
  53. const httpsServer = Https.createServer({
  54. //key: Fs.readFileSync("/home/tom/node.js/websocket_ex1/private.key"),
  55. //cert: Fs.readFileSync("/home/tom/node.js/websocket_ex1/certificate.crt")
  56. key: Fs.readFileSync("./iot.twgigatech.cn.key"),
  57. cert: Fs.readFileSync("./iot.twgigatech.cn.crt")
  58. });
  59. const wss = new WebSocketServer({
  60. server: httpsServer
  61. });
  62. httpsServer.on('request', (req, res) => {
  63. res.writeHead(200);
  64. res.end('hello HTTPS world\n');
  65. });
  66. wss.on('connection', (ws) => {
  67. console.log(`[WSS SERVER] connection()`);
  68. ws.clientId = uuid.v1();
  69. wssclients[ws.clientId] = ws;
  70. console.log('client connected:'+ws.clientId);
  71. ws.on('message', function (message) {
  72. console.log(`[WSS SERVER] Received: ${message}`);
  73. /*
  74. ws.send(`ECHO: ${message}`, (err) => {
  75. if (err) {
  76. console.log(`[WSS SERVER] error: ${err}`);
  77. }
  78. });
  79. */
  80. try{
  81. const data = JSON.parse(message)
  82. switch(data.cmd){
  83. case BERRY_PI:
  84. //client.publish('CAMERA/PHOTO', ws.clientId)
  85. wssclients[ws.clientId].send(JSON.stringify({
  86. cmd:"CAMERA/PHOTO",
  87. //path: "http://iot.gigatech.tw:8000/pic/01.jpg"
  88. path: "http://iot.twgigatech.cn:8090/image/0"+curcnt+".jpg"
  89. }));
  90. if (curcnt==1) {
  91. curcnt++;
  92. cmd.run('avconv -y -i rtsp://203.73.93.26:554/video1 -an -vframes 1 //home/tom/node.js/websocket_ex1/public/image/06.jpg');
  93. console.log(`Get picture!!!!`);
  94. }
  95. else if (curcnt==6) curcnt=1;
  96. else curcnt++;
  97. return;
  98. case LOGIN:
  99. request.get({
  100. uri: 'https://api.weixin.qq.com/sns/jscode2session',
  101. json: true,
  102. qs: {
  103. grant_type: 'authorization_code',
  104. appid: appId,
  105. secret: appSecret,
  106. js_code: data.code
  107. }
  108. }, (err, response, data) => {
  109. if (response.statusCode === 200) {
  110. //TODO: 生成一个唯一字符串sessionid作为键,将openid和session_key作为值,存入redis,超时时间设置为2小时
  111. let secretValue = {
  112. openid: data.openid,
  113. session_key: data.session_key,
  114. unionid: data.unionid
  115. }
  116. console.log("OPEDID:"+data.openid+" ,SessionKey:"+data.session_key+" ,unionid:"+data.unionid);
  117. }
  118. })
  119. return;
  120. case FORMID:
  121. formid = data.formId;
  122. request.get({
  123. uri: 'https://api.weixin.qq.com/cgi-bin/token',
  124. json: true,
  125. qs: {
  126. grant_type: 'client_credential',
  127. appid: appId,
  128. secret: appSecret
  129. }
  130. }, (err, response, data) => {
  131. if (response.statusCode === 200) {
  132. //TODO: 生成一个唯一字符串sessionid作为键,将openid和session_key作为值,存入redis,超时时间设置为2小时
  133. let secretValue = {
  134. token: data.access_token,
  135. expires: data.expires_in
  136. }
  137. console.log("TOKEN:"+data.access_token+" ,EXPIRES:"+data.expires_in+" FormID:"+formid);
  138. /*
  139. var options = {
  140. uri: 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='+data.access_token,
  141. method: 'POST',
  142. body: {
  143. touser: 'oWxou5YnNOYAGrY676WQ057_DkWE',
  144. template_id: 'XiCgsxm-DH73hmAF0CJdlw4MORSDDcUXepF8vxRQz8A',
  145. //page: '点击模版卡片的跳转页面',
  146. form_id: formid,
  147. data: {
  148. keyword1:{
  149. value: '小程序测试模版',
  150. color: '#173177'
  151. },
  152. keyword2:{
  153. value: '2017年3月24日',
  154. color: '#173177'
  155. },
  156. keyword3:{
  157. value: 'iHleath',
  158. color: '#173177'
  159. }
  160. },
  161. //需要放大的关键字
  162. //emphasis_keyword: 'keyword1.DATA'
  163. }
  164. };
  165. request (options, function (error, response, body) {
  166. if (!error && response.statusCode == 200) {
  167. console.log(body.id) // Print the shortened url.
  168. }
  169. });
  170. */
  171. // Set the headers
  172. // Configure the request
  173. var nowDate = new Date();
  174. var result = nowDate.toLocaleDateString() + " "+ nowDate.toLocaleTimeString();
  175. var options = {
  176. uri: 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='+data.access_token,
  177. method: 'POST',
  178. json: true,
  179. body: {
  180. touser: 'oWxou5YnNOYAGrY676WQ057_DkWE',
  181. //touser: 'oWxou5WRP3pWQOhAz9I9YAjVgo5Q',
  182. template_id: 'XiCgsxm-DH73hmAF0CJdlw4MORSDDcUXepF8vxRQz8A',
  183. //page: '点击模版卡片的跳转页面',
  184. form_id: formid,
  185. data: {
  186. keyword1:{
  187. value: '小程序测试模版',
  188. color: '#173177'
  189. },
  190. keyword2:{
  191. //value: '2018年3月6日9時53分',
  192. value: result,
  193. color: '#173177'
  194. },
  195. keyword3:{
  196. value: 'Gigatech小區',
  197. color: '#173177'
  198. }
  199. },
  200. //需要放大的关键字
  201. emphasis_keyword: 'keyword1.DATA'
  202. }
  203. }
  204. // Start the request
  205. request(options, function (error, response, body) {
  206. if (!error && response.statusCode == 200) {
  207. // Print out the response body
  208. console.log(body)
  209. }
  210. })
  211. }
  212. })
  213. return;
  214. case ENCRYPT:
  215. encryptedData = data.encryptedData;
  216. iv = data.iv;
  217. request.get({
  218. uri: 'https://api.weixin.qq.com/sns/jscode2session',
  219. json: true,
  220. qs: {
  221. grant_type: 'authorization_code',
  222. appid: appId,
  223. secret: appSecret,
  224. js_code: data.code
  225. }
  226. }, (err, response, data) => {
  227. if (response.statusCode === 200) {
  228. //TODO: 生成一个唯一字符串sessionid作为键,将openid和session_key作为值,存入redis,超时时间设置为2小时
  229. let secretValue = {
  230. openid: data.openid,
  231. session_key: data.session_key,
  232. }
  233. console.log("OPEDID:"+data.openid+" ,SessionKey:"+data.session_key);
  234. var pc = new WXBizDataCrypt(appId, data.session_key);
  235. var decode_data = pc.decryptData(encryptedData , iv);
  236. console.log("Name:"+decode_data.nickName+", unionId:"+ decode_data.unionId);
  237. console.log(decode_data);
  238. }
  239. })
  240. return;
  241. default:
  242. return;
  243. }
  244. }catch(e){
  245. console.log(e)
  246. }
  247. });
  248. ws.on('close', () => {
  249. console.log(`[WSS SERVER] close`);
  250. if(ws.clientId) {
  251. delete wssclients[ws.clientId];
  252. console.log('wssclient:'+ws.clientId);
  253. }
  254. });
  255. });
  256. httpsServer.listen(443);
  257. console.log("secure websocketServer Listen port : 443");
  258. var app = express();
  259. app.use(express.static(path.join(__dirname, 'public')));
  260. app.listen(8090, () => {
  261. console.log(`App listening at port 8090`)
  262. })