onenet.js 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. import {getToken} from './token'
  2. import { MyMqttManager } from '@/uni_modules/flight-mqtt';
  3. export class Onenet {
  4. url = "tcp://mqtts.heclouds.com:1883"
  5. productId = ""
  6. deviceName = ""
  7. secretKey = ""
  8. userId = "" //用户id
  9. userSecretKey = "" //用户 访问秘钥
  10. mqtt = null
  11. dataId = 1 // 上传数据时的编号
  12. topics = {} //主题及对应的处理方法
  13. /**
  14. * @param {string} pid 产品Id
  15. * @param {string} dn 设备名称
  16. * @param {string} sk 产品秘钥
  17. * @param {string} usk 用户账号访问秘钥
  18. * @param {string} url onenet 链接服务器地址, 默认为"tcp://mqtts.heclouds.com:1883"
  19. */
  20. constructor(pid, dn, sk, usk, uid, url){
  21. if(!!url){
  22. this.url = url
  23. }
  24. this.productId = pid
  25. this.deviceName = dn
  26. this.secretKey = sk
  27. this.userSecretKey = usk
  28. this.userId = uid
  29. }
  30. /**
  31. * @param {Object} topic 接收到的publish 主题
  32. * @param {Object} content 接收到的publish 载荷
  33. */
  34. receiveProcess(topic, content){
  35. console.log(topic, content)
  36. }
  37. connectParam(pid, dn, sk) {
  38. const res = `products/${pid}/devices/${dn}`;
  39. const token = getToken(res, "sha1", sk)
  40. return {
  41. clientId: dn,
  42. username: pid,
  43. password: token
  44. }
  45. }
  46. connectMqttServer(){
  47. const mqtt = new MyMqttManager()
  48. mqtt.on(this.receiveProcess)
  49. let param = this.connectParam(this.productId, this.deviceName, this.secretKey)
  50. mqtt.connect(this.url, param.clientId, param.username, param.password);
  51. mqtt.initCallback();
  52. this.mqtt = mqtt
  53. }
  54. subscript(type, fn){
  55. this.mqtt.subscript(this.generateTopic(type))
  56. this.topics[type] = fn
  57. }
  58. publishRealData(fn){
  59. let data = fn()
  60. let real = {
  61. "id": (this.dataId++).toString(),
  62. "version": "1.0",
  63. "params": {}
  64. }
  65. if(typeof data === "string") {
  66. try{
  67. data = JSON.parse(data)
  68. }catch(e){
  69. //TODO handle the exception
  70. console.log("传入数据格式错误")
  71. return
  72. }
  73. }
  74. const keys = Object.keys(data);
  75. const timestamp = Date.now();
  76. keys.forEach((key) => {
  77. const value = data[key];
  78. real.params[key] = {
  79. time: timestamp,
  80. value: value
  81. }
  82. });
  83. this.mqtt.publish(this.generateTopic("property"), JSON.stringify(real))
  84. }
  85. generateTopic(type) {
  86. switch(type) {
  87. case "property":
  88. return `$sys/${this.productId}/${this.deviceName}/thing/property/post`
  89. case 'propertyRespond':
  90. return `$sys/${this.productId}/${this.deviceName}/thing/property/post/reply`
  91. case "setProperty":
  92. return `$sys/${this.productId}/${this.deviceName}/thing/property/set`
  93. case 'setPropertyRespond':
  94. return `$sys/${this.productId}/${this.deviceName}/thing/property/set/reply`
  95. default:
  96. return `$sys/${this.productId}/${this.deviceName}/thing/property/get`
  97. }
  98. }
  99. apiParam(uid, usk) {
  100. const res = `userid/${uid}`;
  101. const token = getToken(res, "sha1", usk)
  102. return token
  103. }
  104. uploadFile(file) {
  105. return new Promise((resolve, reject) => {
  106. uni.uploadFile({
  107. url: 'https://iot-api.heclouds.com/device/file-upload',
  108. filePath: file,
  109. name: "file",
  110. formData: {
  111. imei: this.deviceName,
  112. device_name: this.deviceName,
  113. product_id: this.productId
  114. },
  115. header:{
  116. authorization: this.apiParam(this.userId, this.userSecretKey)
  117. },
  118. success: uploadFileRes => {
  119. if(uploadFileRes.statusCode == 200) {
  120. // getApp().$loger.log('上传成功', uploadFileRes, file)
  121. console.log('上传成功', uploadFileRes, file)
  122. resolve(uploadFileRes)
  123. }
  124. else
  125. {
  126. // getApp().$loger.log('上传失败', uploadFileRes, file)
  127. console.log('上传失败', uploadFileRes, file)
  128. reject(Error(uploadFileRes.errMsg))
  129. }
  130. },
  131. fail: err => {
  132. // getApp().$loger.log('上传失败', err);
  133. console.log('上传失败', err);
  134. reject(err)
  135. },
  136. complete: console.log
  137. });
  138. })
  139. }
  140. }