User.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  1. // logic : there is a new socket, there is a new user.
  2. import Utils from './Utils.js'
  3. import Logger from './Logger.js'
  4. import Pusher from './Pusher.js'
  5. import Caller from './Caller.js'
  6. import XFiler from './XFile.js'
  7. import Meta from './Meta.js'
  8. import mysql from './MysqlWraper.js'
  9. // import UserList from './UserList.js'
  10. import Report from './Report.js'
  11. import RedisService from "./RedisService.js"
  12. // import metadata from './meta_definition.js'
  13. // import TestPusher from './TestPusher.js'
  14. // let ioClient = require('socket.io-client')
  15. let config = require('./config/appconfig.js')
  16. export default class User {
  17. constructor (io, userlist, metaStore, socket, cardStore, sqlResultStore, callStore, reportFile, workers) {
  18. console.log("构建User")
  19. if (socket) {
  20. console.log("User有Socket")
  21. this.userlist = userlist
  22. this.socket = null
  23. this.session = null
  24. this.io = io
  25. this.bind(socket)
  26. this.name = null // user's name
  27. this.type = null // collector, monitor
  28. this.workers = workers
  29. this.meta = new Meta(reportFile, workers)
  30. this.filer = new XFiler()
  31. this.metaStore = metaStore
  32. this.cardStore = cardStore
  33. this.callSotre = callStore
  34. this.reportFile = reportFile
  35. this.report = new Report(this, metaStore, sqlResultStore)
  36. } else {
  37. console.warn('无可用连接!')
  38. }
  39. }
  40. // 监控端登录时,PUSH 采集服务器的状态
  41. sendCollectorStatus () {
  42. let collector = this.userlist.get(config.COLLECTOR)
  43. let status = collector && collector.socket && collector.socket.auth ? 'online' : 'offline'
  44. let message = {
  45. cmd: 'collector_status',
  46. data: {
  47. status: status,
  48. time: new Date()
  49. }
  50. }
  51. this.socket.emit('PUSH', message)
  52. }
  53. // 采集服务器状态变化时,广播状态
  54. // 注意,采集server logout 的时候,不广播,直接通过 socket 的 disconncet 事件广播
  55. broadcastCollectorStatus (status) {
  56. let message = {
  57. cmd: 'collector_status',
  58. data: {
  59. status: status,
  60. time: new Date()
  61. }
  62. }
  63. this.io.to(config.MONITOR).emit('PUSH', message)
  64. }
  65. sendThreeRate (data) {
  66. console.log('data----------------------', data)
  67. }
  68. registerEventHandler (socket) {
  69. if (!socket) {
  70. console.warn('注册事件处理器失败:没有可用的网络连接!')
  71. return
  72. }
  73. console.log("Socket 事件监听~")
  74. socket.on('disconnect', (req) => {
  75. console.log(`USER ${this.name} disconnected.`)
  76. if (this.name === config.COLLECTOR) {
  77. this.broadcastCollectorStatus('offline')
  78. }
  79. })
  80. socket.on('USER', (req, callback) => {
  81. console.log(`Got USER message : \n\t${JSON.stringify(req)}`)
  82. req = Utils.toJson(req)
  83. if (!req) {
  84. console.warn('Invalid request.', req)
  85. return
  86. }
  87. switch (req.cmd) {
  88. case 'login':
  89. console.log("&&&&&&&&^^^^^^^^^^^^^^^^^^^&&&&&&&&&&&&&&&")
  90. this.login(req, callback)
  91. break
  92. case 'logout':
  93. this.logout(req, callback)
  94. break
  95. case 'standby':
  96. this.standby(req, callback)
  97. break
  98. case 'modify':
  99. this.modify(req, callback)
  100. break
  101. default:
  102. console.warn(`未知的 USER 请求:${req.cmd}`)
  103. break
  104. }
  105. })
  106. socket.on('FILE', (req) => {
  107. console.log("444444444444444444")
  108. console.log(`Got FILE message : \n\t${JSON.stringify(req)}`)
  109. req = Utils.toJson(req)
  110. this.filer.dispatch(socket, req)
  111. })
  112. socket.on('META', (req) => {
  113. // console.log(`Got META message : \n\t${JSON.stringify(req)}`)
  114. let sql = req.data.sql
  115. let bUpdateSettings = false
  116. //设置此字段为超速,server通知采集应用新的配置信息
  117. if (sql.indexOf('dat_setting') != -1 && sql.indexOf('over_speed') != -1)
  118. {
  119. bUpdateSettings = true
  120. }
  121. if (sql.indexOf('dat_map_zhurong') != -1 && sql.indexOf('solution') != -1)
  122. {
  123. bUpdateSettings = true
  124. }
  125. req = Utils.toJson(req)
  126. if (!req) {
  127. console.warn('Invalid request.', req)
  128. return
  129. }
  130. if (socket.auth) {
  131. this.meta.dispatch(this.socket, req)
  132. if (bUpdateSettings)
  133. {
  134. let message = {
  135. cmd: 'setting',
  136. data: {
  137. file_path: 'fileURI'
  138. }
  139. }
  140. socket.server.sockets.emit('CALL', message) // 向所有用户广播,包括自己
  141. }
  142. } else {
  143. this.notLogin('META')
  144. }
  145. })
  146. socket.on('REPT', (req, callback) => {
  147. console.log("########REPT########")
  148. console.log(`Got META message : \n\t${JSON.stringify(req)}`)
  149. req = Utils.toJson(req)
  150. if (!req) {
  151. console.warn('Invalid request.', req)
  152. return
  153. }
  154. if (socket.auth) {
  155. this.report.dispatch(this.socket, req, callback)
  156. } else {
  157. this.notLogin('REPT')
  158. }
  159. })
  160. socket.on('CONTROLLIGHT', (req, callback) => {
  161. req = Utils.toJson(req)
  162. let msg = JSON.stringify(req)
  163. console.log("########CONTROLLIGHT########"+msg)
  164. })
  165. // 客户端发往采集 Server 的消息,Web Server 中转(发送到 room : config.COLLECTOR)
  166. socket.on('CALL', (req) => {
  167. req = Utils.toJson(req)
  168. console.log(JSON.stringify(req));
  169. if (!req) {
  170. console.warn('Invalid request.', req)
  171. return
  172. }
  173. if (socket.auth) {
  174. if (req.cmd === 'helpme_done' || req.cmd === 'req_all_data' || req.cmd === 'gas_done') { // 呼救处理消息通过 CALL 从客户端发送过来,通过 PUSH 广播给其他客户端
  175. socket.broadcast.emit('PUSH', req)
  176. socket.emit('PUSH', req) // response to the sender
  177. if (req.cmd === 'helpme_done') {
  178. Caller.call(socket, req)
  179. }
  180. if (req.cmd === 'helpme_done' || req.cmd === 'req_all_data') {
  181. Logger.log2db(socket, 2, `${req.data.user_id}解除${req.data.id}的呼救`)
  182. }
  183. // socket.to(config.MONITOR).emit('PUSH', req)
  184. } else {
  185. if (req.cmd === 'clear_card') { // 客户端手动升井
  186. console.log("手动升井")
  187. this.cardStore.setHandupdatescards(req)
  188. this.meta.dispatch(this.socket, req)
  189. }
  190. Caller.call(socket, req)
  191. }
  192. } else {
  193. this.notLogin('CALL')
  194. }
  195. })
  196. socket.on('ALARM', (req) => {
  197. // console.log(`Got ALARM message : \n\t${JSON.stringify(req)}`)
  198. req = Utils.toJson(req)
  199. if (!req) {
  200. console.warn('Invalid request.', req)
  201. return
  202. }
  203. if (socket.auth) {
  204. if (req.cmd === 'alarm_done') { // 告警处理消息通过 ALARM 从客户端发送过来,通过 PUSH 广播给其他客户端
  205. socket.broadcast.emit('PUSH', req)
  206. socket.emit('PUSH', req) // response to the sender
  207. // socket.to(config.MONITOR).emit('PUSH', req)
  208. } else {
  209. Caller.call(socket, req)
  210. }
  211. } else {
  212. this.notLogin('ALARM')
  213. }
  214. })
  215. // 采集 Server 发往客户端的消息,Web Server 中转(发送到 room : config.MONITOR)
  216. socket.on('PUSH', (req) => {
  217. console.log(`Got PUSH message : \n\t${JSON.stringify(req)}`)
  218. let self = this
  219. req = Utils.toJson(req)
  220. if (!req) {
  221. console.warn('Invalid request.')
  222. return
  223. }
  224. let datas = Utils.toJson(req.data)
  225. let cmd = req.cmd
  226. this.storePosmapData(datas, cmd)
  227. if (socket.auth) {
  228. //TODO 测试
  229. // cmd = "device_state"
  230. // if(cmd == "device_state"){
  231. // console.log("User.js====PUSH====cmd====device_state")
  232. // console.log(datas)
  233. // let testData = {
  234. // "cmd":"device_state",
  235. // "data":datas,
  236. // "version":"1.0.0.4"
  237. // }
  238. // let msg = JSON.stringify(testData)
  239. // console.log(msg)
  240. // Pusher.push(socket, msg, this.name)
  241. // this.socket.emit('PUSH', msg)
  242. // // this.socket.emit('PUSH', msg)
  243. // // socket.emit('PUSH', msg)
  244. // }
  245. // TODO 后续打开 加上device_state全局广播逻辑
  246. // req.data = JSON.stringify(datas)
  247. if (cmd === 'device_state' || cmd === 'light_state' || cmd === 'tof_data') {
  248. // console.log("User.js====PUSH====cmd====device_state")
  249. let msg = req.data
  250. console.log(req)
  251. this.socket.emit('PUSH', req)
  252. }
  253. if (cmd === 'load_history_completed') {
  254. console.log(req)
  255. this.socket.emit('PUSH', req)
  256. }
  257. Pusher.push(socket, req)
  258. if (cmd === 'up_mine' || cmd === 'pos_map' || cmd === 'resp_all_data') {
  259. let msg = {
  260. cmd: 'nosignal_staffs',
  261. data: {
  262. handuping: this.cardStore.handUpdatescards,
  263. nosignal: this.cardStore.nosignalscars
  264. }
  265. }
  266. Pusher.push(socket, msg, this.name)
  267. }
  268. if (cmd === 'alarm') {
  269. console.log("进来了------"+datas);
  270. this.startGasCall(socket, datas)
  271. }
  272. if (cmd === 'pos_map') {
  273. console.log(req)
  274. this.workers.send({
  275. cmd: cmd,
  276. data: self.cardStore.sdiscards ? Array.from(self.cardStore.sdiscards.values()).length : 0
  277. })
  278. this.callBreatheart() // 向采集发送心跳
  279. }
  280. } else {
  281. this.notLogin('PUSH')
  282. }
  283. })
  284. // 屏蔽掉测试入口
  285. // // 采集 Server 发往客户端的消息,Web Server 中转(发送到 room : config.MONITOR)
  286. // socket.on('TEST', (req) => {
  287. // // console.log(`Got TEST message : \n\t${JSON.stringify(req)}`)
  288. // req = Utils.toJson(req)
  289. // if (!req) {
  290. // console.warn('Invalid request.', req)
  291. // return
  292. // }
  293. // switch (req.cmd) {
  294. // case 'start':
  295. // this.testPusher = new TestPusher('../tmp/testdata/push.json', 980, socket)
  296. // this.testPusher.start()
  297. // break
  298. // case 'stop':
  299. // if (this.testPusher) {
  300. // this.testPusher.stop()
  301. // }
  302. // break
  303. // default:
  304. // console.warn(`未知的 TEST 请求:${req.cmd}`)
  305. // break
  306. // }
  307. // })
  308. socket.on('TIME', (req) => {
  309. let now = new Date()
  310. let hour = now.getHours() < 10 ? '0' + now.getHours() : now.getHours()
  311. let minutes = now.getMinutes() < 10 ? '0' + now.getMinutes() : now.getMinutes()
  312. let seconds = now.getSeconds() < 10 ? '0' + now.getSeconds() : now.getSeconds()
  313. let servertime = hour + ':' + minutes + ':' + seconds
  314. let msg = {
  315. cmd: 'time',
  316. data: {
  317. now: servertime
  318. }
  319. }
  320. this.socket.emit('PUSH', msg)
  321. })
  322. // socket.on('ALL', (msg) => {
  323. // this.requestAllCardPositions(msg)
  324. // })
  325. // 采集 Server 发往客户端的消息,Web Server 中转(发送到 room : config.MONITOR)
  326. socket.on('HELP', (req) => {
  327. // console.log(`Got HELP message : \n\t${JSON.stringify(req)}`)
  328. req = Utils.toJson(req)
  329. for (let i = 0; i < req.length; i++) {
  330. let users = this.userlist.getList()
  331. for (var [key, value] of users) {
  332. let name = key
  333. let type = value.type
  334. let values = Number(req[i].event_id) + ',' + '"' + name + '"' + ',' + '"' + type + '"'
  335. let sql = `INSERT into his_help_event_user VALUES (${values})`
  336. // let sql = `INSERT into his_help_event_user VALUES (1,"lly","lly")`
  337. // let rows = null
  338. try {
  339. mysql.query(sql)
  340. } catch (err) {
  341. console.error(`更新DB失败。 \n\t ${err}`)
  342. }
  343. Pusher.push(socket, req)
  344. }
  345. }
  346. // }
  347. // Pusher.push(socket, req)
  348. // } else {
  349. // let resMsg = {
  350. // code: -1,
  351. // msg: `用户 ${this.name} 尚未登录!`
  352. // }
  353. // socket.emit('USER', resMsg)
  354. // console.warn(resMsg.msg)
  355. // }
  356. })
  357. // 登录后第三方java服务
  358. socket.on('JAVA_SOCKET_LOGINED', (req) => {
  359. console.log("JAVA_SOCKET_TEST")
  360. let reqData = JSON.parse(req)
  361. console.log("||||||||||||||||||||||||")
  362. console.log(reqData.data)
  363. // this.cardStore.setHandupdatescards(reqData)
  364. // this.meta.dispatch(socket, reqData)
  365. })
  366. }
  367. storePosmapData (datas, cmd) {
  368. let data = null
  369. if (cmd === 'up_mine') {
  370. this.cardStore.deleteNosignalCards(datas)
  371. } else if (cmd === 'pos_map') {
  372. data = datas
  373. this.cardStore.cardMove(datas)
  374. } else if (cmd === 'resp_all_data') {
  375. for (let i = 0; i < datas.length; i++) {
  376. let row = datas[i]
  377. if (row.cmd === 'pos_map') {
  378. data = row.data
  379. this.cardStore.cardMove(data)
  380. }
  381. }
  382. }
  383. }
  384. async startGasCall (socket, rows) {
  385. for (let i = 0; i < rows.length; i++) {
  386. let row = rows[i]
  387. console.log(row);
  388. let type = row.type_id
  389. type = parseInt(type, 10)
  390. if (type !== 34 && type !== 35) return;
  391. let msg = null
  392. let time = Number(new Date().getTime())
  393. let objID = null
  394. let objID2 = null
  395. if(type == 41 && row.obj_id.indexOf(":")!=-1){
  396. var arr = row.obj_id.split(":")
  397. objID = arr[0]
  398. objID2 = arr[1]
  399. }else{
  400. objID = Number(row.obj_id)
  401. }
  402. // if (type === 35) { // 呼叫司机
  403. if (row.start_time != 0) {
  404. if (this.callSotre.calling.get(`${type}-${objID}`)) return
  405. let rows = null
  406. try {
  407. let sql = type === 35 ? `select card_id from dat_sensor_driver_map dsdm, dat_staff_extend dse where dsdm.staff_id = dse.staff_id and sensor_id = ${objID};` : `select reader_id from dat_sensor_reader_map where sensor_id = ${objID}`
  408. rows = await mysql.query(sql)
  409. if (rows.length <= 0) return
  410. if (!this.callSotre.calling.get(`${type}-${objID}`)) {
  411. let ret = new Map()
  412. this.callSotre.calling.set(`${type}-${objID}`, ret)
  413. }
  414. let calling = this.callSotre.calling.get(`${type}-${objID}`)
  415. for (let i = 0; i < rows.length; i++) {
  416. let callID = type === 35 ? rows[i].card_id : rows[i].reader_id
  417. type === 35 ? calling.set(callID, {
  418. cardid: callID,
  419. cardtype: 1
  420. }) : calling.set(callID, {
  421. stationid: callID
  422. })
  423. }
  424. let callCards = Array.from(calling.values())
  425. msg = {
  426. cmd: 'call_card_req',
  427. data: {
  428. call_type_id: 1, // 全员呼叫:0 定员呼叫:1
  429. call_time_out: 5, // 呼叫时长
  430. call_level_id: 2, // 呼叫类型 一般呼叫:1 紧急呼叫:2
  431. user_name: 'systrm', // 呼叫人
  432. call_time: time // 呼叫时间戳
  433. }
  434. }
  435. if (type === 35) {
  436. msg.data['stations'] = [{ stationid: 0 }]
  437. msg.data['cards'] = callCards
  438. } else {
  439. msg.data['stations'] = callCards
  440. msg.data['cards'] = []
  441. }
  442. } catch (err) {
  443. console.error(`查询DB失败。 \n\t ${err}`)
  444. return
  445. }
  446. } else if (row.start_time === 0) {
  447. let callCards = this.callSotre.calling.get(`${type}-${objID}`) && Array.from(this.callSotre.calling.get(`${type}-${objID}`).values())
  448. if (callCards && callCards.length > 0) {
  449. msg = {
  450. cmd: 'call_card_cancel_req',
  451. data: {
  452. call_type_id: 1, // 全员/定员
  453. user_name: 'systrm', // 取消人
  454. call_time: time // 时间戳
  455. }
  456. }
  457. if (type === 35) {
  458. msg.data['stations'] = [{ stationid: 0 }]
  459. msg.data['cards'] = callCards
  460. } else {
  461. msg.data['stations'] = callCards
  462. msg.data['cards'] = []
  463. }
  464. }
  465. this.callSotre.calling.delete(`${type}-${objID}`)
  466. }
  467. Caller.call(socket, msg)
  468. }
  469. }
  470. notLogin (cmd) {
  471. let res = {
  472. code: -100, // -100, 表示尚未登录
  473. msg: `${cmd} : 用户 ${this.name} 尚未登录!`,
  474. data: {
  475. username: this.name
  476. }
  477. }
  478. // info the client
  479. this.socket.emit('USER', res)
  480. console.warn(res.msg)
  481. }
  482. doCallBack (fn, msg, remark) {
  483. if (fn && typeof fn === 'function') {
  484. fn(msg)
  485. console.debug(`${remark} : callback is done. callback=${fn}, msg=${msg}`)
  486. } else {
  487. console.warn(`${remark} : callback is invalid. callback=${fn}, msg=${msg}`)
  488. }
  489. }
  490. /**
  491. * login processor
  492. *
  493. * @method login
  494. *
  495. * @param {[type]} req [login message]
  496. * @param {Function} callback [callback the client's processor]
  497. *
  498. */
  499. async login (req, callback) {
  500. console.log("用户登录:")
  501. console.log(req)
  502. console.log(req.data.user_name)
  503. let resMsg = null
  504. let userName = req.data.user_name
  505. let userPass = req.data.user_pass
  506. // userPass = Utils.sha1(userPass)
  507. let sql = `select user_id, dept_id, role_id, access_id, obj_range from dat_user where user_id="${userName}" and pwd="${userPass}"`
  508. // console.log('sql', sql)
  509. let rows = null
  510. try {
  511. console.log('Going to do login-check on DB, please wait... ', userName)
  512. rows = await mysql.query(sql)
  513. // console.log('rows-----------------', rows)
  514. console.log('Login-check on DB done. ', userName)
  515. // let socket = ioClient.connect('http://127.0.0.1:3000')
  516. // socket.emit('new user login', userName)
  517. } catch (err) {
  518. console.error(`查询DB失败。 \n\t ${err}`)
  519. resMsg = {
  520. code: -1,
  521. msg: '服务器错误,请联系系统管理员!',
  522. data: {
  523. name: userName
  524. }
  525. }
  526. this.doCallBack(callback, resMsg, 'User.login')
  527. return
  528. }
  529. if (rows && rows.length > 0) { // loged in
  530. this.socket.auth = true
  531. this.session.user = {
  532. // name: rows[0].user_id,
  533. name: userName,
  534. deptID: rows[0].dept_id,
  535. roleID: rows[0].role_id,
  536. accessID: rows[0].access_id,
  537. objRange: rows[0].obj_range,
  538. ip: this.socket.request.connection.remoteAddress || this.socket.request.connection.localAddress || this.socket.handshake.address
  539. }
  540. this.session.save() // save the session info to sessionStore
  541. // TODO 后续需要加密存储
  542. console.log("存入到Redis")
  543. let redisClient = RedisService.getRedisConnet()
  544. let userMsg = {
  545. user_name: userName,
  546. user_pwd: userPass
  547. }
  548. redisClient.set(userName, JSON.stringify(userMsg))
  549. this.initContext(userName, req)
  550. Logger.log2db(this.socket, 0, '登录成功!')
  551. resMsg = {
  552. code: 0,
  553. msg: '',
  554. data: {
  555. name: userName,
  556. roleID: rows[0].role_id,
  557. deptID: rows[0].dept_id,
  558. accessID: rows[0].access_id,
  559. objRange: rows[0].obj_range,
  560. sid: this.socket.handshake.sessionID,
  561. ip: this.socket.request.connection.remoteAddress || this.socket.request.connection.localAddress || this.socket.handshake.address
  562. }
  563. }
  564. // info all connections
  565. if (this.name === config.COLLECTOR) {
  566. this.broadcastCollectorStatus('online')
  567. } else {
  568. // 只发给刚登录的用户
  569. this.sendCollectorStatus()
  570. }
  571. } else {
  572. console.log('ERROR: 用户名或密码错误: ' + this.name)
  573. resMsg = {
  574. code: -1,
  575. msg: '用户名或密码错误,请确认后再试。'
  576. }
  577. }
  578. this.doCallBack(callback, resMsg, 'User.login')
  579. }
  580. /**
  581. * 退出登录态
  582. * socket 退出对应的房间。
  583. * 注意,这时 client / browser 与 server 之间的 socket 并没有断开。
  584. *
  585. * @method doLogout
  586. *
  587. * @param {[type]} socket [description]
  588. * @param {[type]} event_tag [description]
  589. * @param {[type]} req [description]
  590. *
  591. * @return {[type]} [description]
  592. */
  593. logout (req, callback) {
  594. // let resMsg = null
  595. let userInfo = this.session.user
  596. if (userInfo) {
  597. let userName = userInfo.name
  598. Logger.log2db(this.socket, 1, '退出成功!')
  599. this.clearContext(userName)
  600. delete this.socket.handshake.session.user
  601. this.socket.auth = false
  602. if (this.name === config.COLLECTOR) {
  603. this.broadcastCollectorStatus('offline')
  604. }
  605. // logout no need to inform the client
  606. // let msg = `${userName} loged out.`
  607. // resMsg = {
  608. // code: 0,
  609. // msg: msg
  610. // }
  611. // this.doCallBack(callback, resMsg, 'User.logout')
  612. this.name = null
  613. }
  614. }
  615. standby (req, callback) {
  616. let userName = req.data.username
  617. let resMsg = null
  618. if (req.data.op === 'enter') {
  619. this.socket.leave(config.MONITOR)
  620. console.log(`>> User ${userName} leave ${config.MONITOR}`)
  621. this.socket.join(config.STANDBY)
  622. console.log(`>> User ${userName} enter ${config.STANDBY}`)
  623. resMsg = {
  624. code: 0,
  625. op: req.data.op
  626. }
  627. } else if (req.data.op === 'leave') {
  628. this.socket.leave(config.STANDBY)
  629. console.log(`>> User ${userName} leave ${config.STANDBY}`)
  630. this.socket.join(config.MONITOR)
  631. console.log(`>> User ${userName} enter ${config.MONITOR}`)
  632. resMsg = {
  633. code: 0,
  634. op: req.data.op
  635. }
  636. } else {
  637. resMsg = {
  638. code: -1,
  639. op: req.data.op
  640. }
  641. console.warn('UNKNOWN standby command : ', req.cmd)
  642. }
  643. this.doCallBack(callback, resMsg, 'User.standby')
  644. }
  645. async modify (req, callback) {
  646. let resMsg = null
  647. let username = req.data.username
  648. let oldpwd = req.data.oldpwd
  649. // oldpwd = Utils.sha1(oldpwd)
  650. let newpwd = req.data.newpwd
  651. // newpwd = Utils.sha1(newpwd)
  652. let sql = `select user_id from dat_user where user_id="${username}" and pwd="${oldpwd}"`
  653. let rows = null
  654. try {
  655. rows = await mysql.query(sql)
  656. } catch (err) {
  657. console.error(`查询DB失败。 \n\t ${err}`)
  658. resMsg = {
  659. code: -1,
  660. msg: '服务器错误,请联系系统管理员!',
  661. data: {
  662. name: username
  663. }
  664. }
  665. this.doCallBack(callback, resMsg, 'User.modify')
  666. return
  667. }
  668. // console.log(`Modify password : \n sql : ${sql} \n rows : `, rows)
  669. if (rows && rows.length > 0) { // loged in
  670. sql = `update dat_user set pwd="${newpwd}" where user_id="${username}"`
  671. // execute update on db
  672. rows = null
  673. try {
  674. rows = await mysql.query(sql)
  675. } catch (err) {
  676. console.error(`更新数据库失败 : \n\t SQL : ${sql} \n\t ${err}`)
  677. resMsg = {
  678. code: -1,
  679. msg: '更新数据库失败',
  680. cmd: req.cmd
  681. }
  682. this.doCallBack(callback, resMsg, 'User.modify')
  683. return
  684. }
  685. // 更新 DB 成功
  686. resMsg = {
  687. code: 0,
  688. msg: ''
  689. }
  690. Logger.log2db(this.socket, 3, '修改密码成功!')
  691. } else {
  692. resMsg = {
  693. code: -1,
  694. msg: '用户名或密码错误,请确认后再试。'
  695. }
  696. }
  697. this.doCallBack(callback, resMsg, 'User.modify')
  698. }
  699. bind (socket) {
  700. console.log("Bind")
  701. this.socket = socket
  702. this.socket.auth = true
  703. this.session = socket.handshake.session
  704. this.registerEventHandler(this.socket)
  705. var query = socket.request._query;
  706. console.log(query)
  707. let isDefaultLogin = query.isDefaultLogin;
  708. console.log("isDefaultLogin=====" + isDefaultLogin)
  709. console.log("***********")
  710. if(isDefaultLogin == 'yes') {
  711. console.log("/////////静默登录///////////")
  712. let req = {
  713. cmd: "login",
  714. data: {
  715. "user_name": "admin",
  716. "user_pass": "xcjk@2020#123"
  717. }
  718. }
  719. this.login(req, function() {
  720. console.log("静默登录成功")
  721. });
  722. }
  723. }
  724. initContext (userName, req) {
  725. this.name = userName
  726. // console.log('INIT user context. userName = ', userName)
  727. if (userName === config.COLLECTOR) {
  728. this.type = config.COLLECTOR
  729. this.socket.join(config.COLLECTOR)
  730. console.log(`>> User ${userName} enter ${config.COLLECTOR}`)
  731. Logger.log2db(this.socket, 3, `User ${userName} enter ${config.COLLECTOR}`)
  732. } else {
  733. this.type = config.MONITOR
  734. this.socket.join(config.MONITOR)
  735. console.log(`>> User ${userName} enter ${config.MONITOR}`)
  736. // if a client reconnect, it need to update the client's local meta
  737. // this.meta.dispatch(this.socket, { cmd: 'meta_definition' })
  738. this.meta.sendMetaDefinition(this.socket)
  739. // this.meta.dispatch(this.socket, { cmd: 'card_definition' }) // move to client
  740. // send all meta data and all init card data one by one
  741. // let promises = this.meta.sendAllMetaData(this.socket) // 发送meta_definition中的所有数据
  742. let promises = this.meta.sendDataTable(this.socket) // 发送meta_dat中的数据,基础表更新或删除,每次登陆时,都先发送到客户端
  743. Promise.all(promises).then(() => {
  744. console.log(`>>>> Send all meta data DONE for user ${this.name}.`)
  745. this.requestAllCardPositions()
  746. }).catch((err) => {
  747. console.log(`>>>> Send all meta data FAILED for user ${this.name}.\n`, err)
  748. })
  749. }
  750. this.userlist.add(this) // save socket for later usage
  751. }
  752. clearContext (userName) {
  753. // leave room
  754. if (userName === config.COLLECTOR) {
  755. this.socket.leave(config.COLLECTOR)
  756. console.log(`<< User ${userName} left ${config.COLLECTOR}`)
  757. Logger.log2db(this.socket, 3, `User ${userName} enter ${config.COLLECTOR}`)
  758. } else {
  759. this.socket.leave(config.MONITOR)
  760. console.log(`<< User ${userName} left ${config.MONITOR}`)
  761. }
  762. this.userlist.remove(this)
  763. }
  764. callBreatheart () {
  765. let reqcall = {
  766. cmd: 'beatheart',
  767. data: {}
  768. }
  769. this.io.emit('CALL', reqcall)
  770. // Logger.log2db(this.io, 3, `CALL ${reqcall.cmd}成功`)
  771. }
  772. /**
  773. * 用户登录后,获取当前井下所有卡的位置信息
  774. *
  775. * @method requestAllCardPositions
  776. *
  777. * @param {[type]} socket [description]
  778. *
  779. * @return {[type]} [description]
  780. */
  781. requestAllCardPositions () {
  782. console.log(`Going to send all cards' init position for user ${this.name}.`)
  783. let collector = this.userlist.get(config.COLLECTOR)
  784. let collectorSocket = collector ? collector.socket : null
  785. if (!collectorSocket) {
  786. console.warn('当前没有可用的采集服务器,无法获取现场实时动态。')
  787. return
  788. }
  789. let message = {
  790. cmd: 'req_all_data',
  791. data: '0',
  792. version: '1.0.0.2'
  793. }
  794. let self = this
  795. // console.log('Going to request all data by user ', this.name, message)
  796. collectorSocket.emit('CALL', message, (data) => {
  797. console.log('Got collector\'s response on req_all_data: ', data)
  798. if (data) {
  799. let res = Utils.toJson(data)
  800. Pusher.push(self.socket, res)
  801. // self.socket.emit('PUSH', res) // 将应答结果以 PUSH 的方式发送给客户端(socket) .
  802. }
  803. })
  804. }
  805. }