Server.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. package MqttServer
  2. import (
  3. "Yunlot/conf"
  4. "Yunlot/lib"
  5. "Yunlot/logs"
  6. "Yunlot/models/Device"
  7. "Yunlot/models/Product"
  8. "encoding/json"
  9. "fmt"
  10. beego "github.com/beego/beego/v2/server/web"
  11. "github.com/gin-gonic/gin"
  12. "github.com/yosssi/gmq/mqtt"
  13. "github.com/yosssi/gmq/mqtt/client"
  14. "plugin"
  15. "strconv"
  16. "strings"
  17. "time"
  18. )
  19. var cli *client.Client
  20. func Run_MqttServer() {
  21. time.Sleep(3 * time.Second)
  22. logs.Println("============Run_MqttServer=============", "")
  23. HTTPPort, _ := beego.AppConfig.String("HTTPPort")
  24. // Create an MQTT Client.
  25. cli = client.New(&client.Options{
  26. // Define the processing of the error handler.
  27. ErrorHandler: func(err error) {
  28. logs.PrintlnError("err!!!!!! Run_MqttServer:", err.Error())
  29. time.Sleep(3 * time.Second)
  30. go Run_MqttServer() // MQTT 通讯
  31. return
  32. },
  33. })
  34. // Terminate the Client.
  35. defer cli.Terminate()
  36. c := client.ConnectOptions{
  37. Network: "tcp",
  38. Address: conf.MqttServer_Url,
  39. ClientID: []byte(conf.MqttServer_ClientID + HTTPPort),
  40. UserName: []byte(conf.MqttServer_Username),
  41. Password: []byte(conf.MqttServer_Password),
  42. }
  43. logs.Println("Address:", c.Address)
  44. logs.Println("ClientID:", string(c.ClientID))
  45. // Connect to the MQTT Server.
  46. err := cli.Connect(&c)
  47. if err != nil {
  48. logs.Println("MqttServer", "连接MQTT失败 [cli.Connect]", "")
  49. logs.Println("err!!!!!! Run_MqttServer:", "连接MQTT失败:", err)
  50. fmt.Println("err!!!!!! 连接MQTT失败:", err)
  51. cli.Terminate()
  52. time.Sleep(3 * time.Second)
  53. go Run_MqttServer() // MQTT 通讯
  54. return
  55. }
  56. // Subscribe to topics.
  57. err = cli.Subscribe(&client.SubscribeOptions{
  58. SubReqs: []*client.SubReq{
  59. &client.SubReq{
  60. TopicFilter: []byte("#"),
  61. QoS: mqtt.QoS0,
  62. // Define the processing of the message handler.
  63. Handler: func(topicName, message []byte) {
  64. logs.PrintlnMqtt("<-" + string(topicName) + " " + string(message))
  65. messagePubHandler(string(topicName), message)
  66. },
  67. },
  68. &client.SubReq{ // 设备断开
  69. TopicFilter: []byte("$SYS/brokers/+/clients/+/disconnected"),
  70. QoS: mqtt.QoS0,
  71. // Define the processing of the message handler.
  72. Handler: func(topicName, message []byte) {
  73. logs.PrintlnMqtt("<-" + string(topicName) + " " + string(message))
  74. MessageDisconnected(string(topicName), message)
  75. },
  76. },
  77. &client.SubReq{ // 设备上线
  78. TopicFilter: []byte("$SYS/brokers/+/clients/+/connected"),
  79. QoS: mqtt.QoS0,
  80. // Define the processing of the message handler.
  81. Handler: func(topicName, message []byte) {
  82. logs.PrintlnMqtt("<-" + string(topicName) + " " + string(message))
  83. MessageConnected(string(topicName), message)
  84. },
  85. },
  86. },
  87. })
  88. if err != nil {
  89. logs.Println("MqttServer", "订阅消息 [cli.Subscribe]", "")
  90. logs.Println("err!!!!!! Run_MqttServer:", "连接MQTT失败:", err)
  91. }
  92. fmt.Println("MQTT ok!")
  93. // 创建一个Gin路由器
  94. r := gin.Default()
  95. // 定义路由
  96. r.POST("/authentication", func(c *gin.Context) {
  97. var json struct {
  98. Clientid string `json:"clientid"`
  99. Username string `json:"username"`
  100. Password string `json:"password"`
  101. }
  102. if err := c.Bind(&json); err != nil {
  103. c.JSON(200, gin.H{
  104. "result": "deny", // 认证结果 可选 "allow" | "deny" | "ignore"
  105. "is_superuser": false, // 超级用户 可选 true | false,该项为空时默认为 false
  106. })
  107. return
  108. }
  109. // 保证 Clientid唯一,否则会 下线
  110. if json.Clientid != json.Username {
  111. c.JSON(200, gin.H{
  112. "result": "deny", // 认证结果 可选 "allow" | "deny" | "ignore"
  113. "is_superuser": false, // 超级用户 可选 true | false,该项为空时默认为 false
  114. })
  115. return
  116. }
  117. Device_r := Device.Device{
  118. T_sn: json.Username,
  119. }
  120. // 判断是否存在
  121. if !Device_r.Read_Tidy() {
  122. c.JSON(200, gin.H{
  123. "result": "deny", // 认证结果 可选 "allow" | "deny" | "ignore"
  124. "is_superuser": false, // 超级用户 可选 true | false,该项为空时默认为 false
  125. })
  126. return
  127. }
  128. // 判断密码是否正确
  129. if Device_r.T_password != json.Password {
  130. c.JSON(200, gin.H{
  131. "result": "deny", // 认证结果 可选 "allow" | "deny" | "ignore"
  132. "is_superuser": false, // 超级用户 可选 true | false,该项为空时默认为 false
  133. })
  134. return
  135. }
  136. c.JSON(200, gin.H{
  137. "result": "allow", // 可选 "allow" | "deny" | "ignore"
  138. "is_superuser": false, // 可选 true | false,该项为空时默认为 false
  139. })
  140. })
  141. r.POST("/Acl", func(c *gin.Context) {
  142. logs.Println("Acl!!")
  143. var json struct {
  144. Clientid string `json:"clientid"`//${clientid} — 客户端的 ID。
  145. Username string `json:"username"`//${username} — 客户端登录是用的用户名。
  146. Peerhost string `json:"peerhost"`//${peerhost} — 客户端的源 IP 地址。
  147. Proto_name string `json:"proto_name"`//${proto_name} — 客户端使用的协议名称。例如 MQTT,CoAP 等。
  148. Mountpoint string `json:"mountpoint"`//${mountpoint} — 网关监听器的挂载点(主题前缀)。
  149. Action string `json:"action"`//${action} — 当前执行的动作请求,例如 publish,subscribe。
  150. Topic string `json:"topic"`//${topic} — 当前请求想要发布或订阅的主题(或主题过滤器)
  151. }
  152. if err := c.Bind(&json); err != nil {
  153. c.JSON(200, gin.H{
  154. "result": "deny", // 可选 "allow" | "deny" | "ignore"
  155. })
  156. }
  157. fmt.Println("json:",json)
  158. if json.Username == "admin" {
  159. c.JSON(200, gin.H{"result": "allow"})
  160. return
  161. }
  162. if json.Username == "test" {
  163. c.JSON(200, gin.H{"result": "allow"})
  164. return
  165. }
  166. // 保证 Clientid唯一,否则会 下线
  167. if json.Clientid != json.Username {
  168. c.JSON(200, gin.H{"result": "deny"})
  169. return
  170. }
  171. Device_r := Device.Device{
  172. T_sn: json.Username,
  173. }
  174. // 判断是否存在
  175. if !Device_r.Read_Tidy() {
  176. c.JSON(200, gin.H{"result": "deny"})
  177. return
  178. }
  179. //topic /sub/SN /pub/SN
  180. topic_list := strings.Split(json.Topic,"/")
  181. for _,v := range topic_list{
  182. if len(v) < 7 {
  183. continue // 不是有效SN
  184. }
  185. if v == Device_r.T_sn {
  186. c.JSON(200, gin.H{"result": "allow"})
  187. return
  188. }
  189. }
  190. logs.Println("MQTT Acl E!topic_list:",topic_list)
  191. c.JSON(200, gin.H{"result": "deny"})
  192. return
  193. //
  194. //Clientid_list := strings.Split(username+"_s", "_")
  195. //username = Clientid_list[0]
  196. //if topic_list[2] != username {
  197. // fmt.Println("topic_list[2] != username",topic_list[2])
  198. // c.JSON(200, gin.H{"result": "deny"})
  199. // return
  200. //}
  201. //c.JSON(200, gin.H{"result": "allow"})
  202. //return
  203. })
  204. r.Run(":8080")
  205. }
  206. // 开始处理
  207. func messagePubHandler(topicName string, message []byte) {
  208. // 本地测试
  209. logs.Println("=", "============= Mqtt2 JSON =============")
  210. logs.Println("<-"+topicName, string(message))
  211. // 过滤
  212. topicNameS := strings.Split(topicName, "/")
  213. if len(topicNameS) == 1 {
  214. logs.Println("MqttServer", "订阅地址错误 len(topicNameS) == 1", strconv.Itoa(len(topicNameS)))
  215. return
  216. }
  217. // 验证设备
  218. Device_r := Device.Device{}
  219. for _, sn := range topicNameS {
  220. if len(sn) < 7 {
  221. continue // 不是有效SN
  222. }
  223. Device_r.T_sn = sn
  224. if Device_r.Read_Tidy() {
  225. if Device_r.T_state == 3 {
  226. continue // 不是有效SN
  227. }
  228. break
  229. }
  230. }
  231. if Device_r.T_state != 1 {
  232. logs.Println("MqttServer", Device_r.T_sn+" 设备未激活")
  233. return
  234. }
  235. // 设备类型
  236. ProductType_r := Product.ProductType{T_ProductID: Device_r.T_ProductID}
  237. if !ProductType_r.Read() {
  238. logs.Println("MqttServer", Device_r.T_sn+"|"+Device_r.T_ProductID+" 设备类型找不到!")
  239. return
  240. }
  241. // 设备协议
  242. ProductProt_r := Product.ProductProt{Id: ProductType_r.T_prot}
  243. if !ProductProt_r.Read() {
  244. logs.Println("MqttServer", Device_r.T_sn+"|"+Device_r.T_ProductID+"-"+ fmt.Sprintf("%d",ProductType_r.T_prot)+" 设备协议找不到!")
  245. return
  246. }
  247. // 根据库的存放路径加载库
  248. p, err := plugin.Open(conf.Analysis_Dir + ProductProt_r.T_analysis)
  249. if err != nil {
  250. println(err)
  251. panic(any(err))
  252. }
  253. if topicName[len(topicName)-6:] == "_reply" {
  254. // 返回数据
  255. s, err := p.Lookup("T_reply")
  256. if err != nil {
  257. println(err)
  258. panic(any(err))
  259. }
  260. // 类型转换
  261. f := s.(func(b []byte) []byte)(message)
  262. // 开始处理
  263. println(f)
  264. } else {
  265. var Rt_r = lib.Rt{Status: 200, Msg: "ok"}
  266. // 查找库导出信息
  267. s, err := p.Lookup("R")
  268. if err != nil {
  269. println(err)
  270. panic(any(err))
  271. }
  272. // 类型转换
  273. f := s.(func(b []byte) []byte)(message)
  274. // 开始处理
  275. println(f)
  276. a := string(f[0])
  277. println("首字符:", a)
  278. if a != "{" {
  279. //结构体
  280. var json_r map[string]interface{}
  281. err = json.Unmarshal(f, &json_r)
  282. if err != nil {
  283. Rt_r.Status = 203
  284. goto Mreturn
  285. }
  286. //Handle.AnalysisMap(Device_r, ProductType_r, json_r, "")
  287. } else {
  288. //列表
  289. var json_lr []map[string]interface{}
  290. err = json.Unmarshal(f, &json_lr)
  291. if err != nil {
  292. Rt_r.Status = 203
  293. goto Mreturn
  294. }
  295. //for _, value := range json_lr {
  296. // //Handle.AnalysisMap(Device_r, ProductType_r, value, "")
  297. //}
  298. }
  299. // 返回
  300. Mreturn:
  301. data, _ := json.Marshal(Rt_r)
  302. fmt.Println(string(data))
  303. // 查找库导出信息
  304. s, err = p.Lookup("R_reply")
  305. if err != nil {
  306. println(err)
  307. panic(any(err))
  308. }
  309. // 类型转换
  310. f = s.(func(b []byte) []byte)(data)
  311. // 返回数据
  312. Mqtt_publish(topicName+"_reply", f)
  313. }
  314. }
  315. // 发送数据
  316. func Mqtt_publish(topic string, b []byte) {
  317. // Publish a message.
  318. err := cli.Publish(&client.PublishOptions{
  319. QoS: mqtt.QoS0,
  320. TopicName: []byte(topic),
  321. Message: b,
  322. })
  323. logs.PrintlnMqtt("-> " + topic + "_reply " + string(b))
  324. if err != nil {
  325. logs.PrintlnError("MqttServer", "发送消息失败 [Mqtt_publish]", "-> "+topic+" "+string(b))
  326. }
  327. }