MQTT应用之 emqx部署

先放上用户指南:用户指南 (User Guide) | EMQX 文档

1,安装配置服务器

1, 系统windows2012

2,服务器IIS7.0

3,安装EMQX

4,安装EMQX测试工具

5,数据库版本 sqlserver2008,开发数据库远程登录端口(数据库上配置)

6,开发服务器端口,EMQX 发送端口默认为8085,硬件设备为8013

一、emqx开源前置机

1、下载emqx,地址:https://www.emqx.io/downloads/broker/v3.2.4/emqx-windows-v3.2.4.zip

2、解压缩emqx文件夹到D:\下;

3、启动emqx,详见https://docs.emqx.cn/broker/v3.0/install.html#windows;

4、登录系统,默认admin/public

5、获取http接口地址,https://docs.emqx.cn/broker/v3.0/guide.html#http-%E5%8F%91%E5%B8%83%E6%8E%A5%E5%8F%A3

6、配置应用,获取appid、appsecret,地址:http://[外网地址]:18083/#/applications

7、配置emqx_web_hook,

 地址:http://[外网地址]:18083/#/plugins/ZW1xeEAxMjcuMC4wLjE=/emqx_web_hook

二、epba数据接口

1、解压缩ebpa.front.dataserver文件夹到D:\Web下;

2、配置目录1.21.0703下的web.config文件

----------------------------------

<!-- 数据库套接字 -->

<add name="DbConnection" connectionString="data source=[数据库地址],8002;initial catalog=ebpa;persist security info=True;user id=sa;password=kfw123456;Max Pool Size = 5120;MultipleActiveResultSets = True;App=epba" providerName="System.Data.SqlClient" />

<add name="LogConnection" connectionString="data source=[数据库地址],8002;initial catalog=ebpa;persist security info=True;user id=sa;password=kfw123456;Max Pool Size = 5120;MultipleActiveResultSets = True;App=epba" providerName="System.Data.SqlClient" />

<!-- 对接emqx -->

<add key="EmqxUrl" value="http://[外网地址]:8085/api/v3/mqtt/publish"/><!-- 第一部分的第5点 -->

<add key="EmqxAppId" value="应用的账号"/><!-- 第一部分的第6点 -->

<addkey="EmqxAppSecrct" value="应用的密码"/><!-- 第一部分的第6点 -->

----------------------------------

3、在IIS中添加网站dataServer,物理路径指向D:\Web\ebpa.front.dataserver\1.21.0703,

4、设置网站dataServer的端口为8010;

5、测试接口

  本服务器:http://localhost:8010/api/emq/version

  外网:http://[外网地址]:8010/api/emq/version

  查看是否有以下数据返回

-----------------------------------

{"Data":{"Version":"1.21.703.20793","ServiceTime":"2021-07-03 14:06:29.535"},"Code":0,"Message":""}

-----------------------------------

三、需要在防火墙上开放的端口(统一端口)

数据库端口:8002

emqx的后台端口:10183

emqxhttp端口:8085(下发to端口,需要在接口程序dataserver里关联设置)

epbahttp端口(接口程序IIS部署的端口):8010(上发from,只需要在emqxweb_hook做配置)

epbahttp端口:1883(硬件设备端口)

发送消息到emqx服务器需要在emqx后台创建一个应用账号

 

踩坑记录

1,emqx,配置web_hook 钩子,接受端口8010,需重启后才会生效,记得要配置全路径,不要只写IP和端口
2,配置发送端口8085,需重启后才会生效。
3,电脑重新后要重新emqx start 启动服务,钩子默认会关闭,也要启动起来

配置说明;

下发to需要修改配置文件的端口:D:\emqx-windows-v3.2.4\emqx\etc\plugins\emqx_management 端口改成8085
接受:
emqx的后台端口:10183
emqx的http端口:8085(下发to端口,需要在接口程序dataserver里关联设置)
epba的http端口(接口程序IIS部署的端口):8010(上发from,只需要在emqx里web_hook做配置)要完整的路径,如127.0.0.1:8010/DataServer


epba的http端口:1883(硬件设备端口)

发送消息到emqx服务器需要在emqx后台创建一个应用账号
 
然后吧appid和密码配置到发送函数的header里

以下为测试代码

 public class DataServerController : Controller
    {
        private readonly IHostEnvironment _hostingEnvironment;

        public DataServerController(IHostEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }
        

        //接收EMQX服务器数据
        public async Task<string> DataReceive()
        {
            var request = HttpContext.Request;
            request.EnableBuffering();
            var postJson = "";
            var stream = HttpContext.Request.Body;
            long? length = HttpContext.Request.ContentLength;
            if (length != null && length > 0)
            {
                // 使用这个方式读取,并且使用异步
                StreamReader streamReader =  new StreamReader(stream, Encoding.UTF8);
                postJson = await streamReader.ReadToEndAsync();
               

            }
            HttpContext.Request.Body.Position = 0;

         
            Newtonsoft.Json.Linq.JObject rst = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(postJson);
            var action = rst["action"].ToString();
            var topic = rst["topic"].ToString();
            var payload = rst["payload"].ToString();
            var aa = "";

            //解析内容
            if (action == "message_publish"|| action == "message_deliver")//接受上发的数据
            {
                //接受监控警报
                if (topic.IndexOf("acd") > 0)
                {
                    try
                    {
                        Newtonsoft.Json.Linq.JObject jo2 = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(payload.ToString());

                        if (jo2["message"].ToString() == "1")
                        {

                            //公众号通知预警信息
                            string ACCESS_TOKEN = WxGet.RequestAccessToken();
                            var Title = "您好,您的监控设备发生了车辆感应事件。";
                            var Detail = jo2["ClientID"].ToString();
                            var ramk = "距离" + jo2["distance"].ToString() + "厘米,请及时查看";
                            var CaneraSN = jo2["CaneraSN"].ToString();
                            //发送通知
                            // 李
                              postJson += CommonFunction.Send_YSYTemp("oO1-HxCqwX4l8PkbQA6td0TNO-Dc", ACCESS_TOKEN, CaneraSN, Title, Detail, DateTime.Now.ToString(), ramk);
                            //孔
                             postJson += CommonFunction.Send_YSYTemp("oO1-HxIj0kZFkcjgXvneSEUqxgAk", ACCESS_TOKEN, CaneraSN, Title, Detail, DateTime.Now.ToString(), ramk);
                            aa += "ok";

                        }
                        else
                        {
                            aa += "nnoooo";
                        }
                    }
                    catch (Exception e1)
                    {
                        aa += e1.ToString();
                    }
                }


                获取设备传输的主体内容
                //Newtonsoft.Json.Linq.JObject Exqxjo = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(payload.ToString());

                获取消息主体信息
                //var GateWayID = topic.Substring(9);
                //var SysTime = Convert.ToDateTime(Exqxjo["SysTime"].ToString());
                //var bid = Exqxjo["bid"].ToInt();
                //var mid = Exqxjo["mid"].ToString();
                //var children = Exqxjo["Children"].ToString();
              
                解析携带的孩子节点数据
                //Newtonsoft.Json.Linq.JArray jArray = Newtonsoft.Json.Linq.JArray.Parse(children);

                //for (int i = 0; i < jArray.Count; i++)
                //{
                //    //循环增加网关携带的孩子节点记录
                //    Model.ePa_data_201 model = new Model.ePa_data_201();
                //    model.GateWayID = GateWayID;
                //    model.SysTime = DateTime.Now;
                //    model.bid = bid;
                //    model.mid = mid;
                //    model.ClientID = jArray[i]["ClientID"].ToString();
                //    model.Voltage = CommonFunction.NoHTML(jArray[i]["Voltage"].ToString().Replace("[", "").Replace("]", "").Replace(" ", ""));
                //    model.Current = CommonFunction.NoHTML(jArray[i]["Current"].ToString().Replace("[", "").Replace("]", "").Replace(" ", ""));
                //    model.Power = CommonFunction.NoHTML(jArray[i]["Power"].ToString().Replace("[", "").Replace("]", "").Replace(" ", ""));
                //    model.Energy = CommonFunction.NoHTML(jArray[i]["Energy"].ToString().Replace("[", "").Replace("]", "").Replace(" ", ""));
                //    model.Temperature = CommonFunction.NoHTML(jArray[i]["Temperature"].ToString().Replace("[", "").Replace("]", "").Replace(" ", ""));
                //    model.ElectricStatus = jArray[i]["ElectricStatus"].ToInt();
                //    model.SwitchStatus = jArray[i]["SwitchStatus"].ToInt();
                //    model.UsartComm = jArray[i]["UsartComm"].ToInt();
                //    model.ModifyTime = DateTime.Now;

                //    //model.UserId = UserId;
                //    var dt = SqlSugarUse.CreateSqlServer().Insertable(model).ExecuteCommand();

                //    //判断警报并发送
                //    SendMessage.SendData(model.ClientID, model.Current, model.ElectricStatus.ToString(), model.Temperature);


                //}


            }

            //开始记录日志
            string FilePath = _hostingEnvironment.ContentRootPath + "/EpaLog/EpaLgo.txt";

            var line = System.IO.File.ReadAllText(FilePath);

            //写入文件
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(System.IO.File.Create(FilePath)))
            {
                file.WriteLine(line.ToString() + postJson.ToString()+ topic+ action+aa);
            }


            return postJson;
        }

        //发送EMQX服务器http消息(成功的例子,非必要别改)
        public string DataSend()
        {
            string gateWayId = "GW00000160";
            string topic = "to/epa/" + gateWayId;
            string payload = "{A:1}";
            string url = CommonData.EmqxSend_Post + "/api/v3/mqtt/publish";

            try
            {
                if (string.IsNullOrWhiteSpace(url))
                    throw new Exception("尚未配置url");

                #region REQUEST
                string sret = null;

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/json;charset=utf-8";
                request.Timeout = 60 * 1000;
                request.ProtocolVersion = HttpVersion.Version11;
                // 设置HTTP头Http Basic认证
                string authorization = "emqx应用创建的账号" + ":" + "应用的密码";
                string base64 = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(authorization));
                request.Headers.Add("Authorization", "Basic " + base64);

                #endregion

                #region 数据
                Dictionary<string, object> model = new Dictionary<string, object>();
                model["topic"] = topic;
                model["payload"] = payload;
                model["qos"] = 1;
                model["retain"] = false;
                model["client_id"] = gateWayId;

                var requestData = Newtonsoft.Json.JsonConvert.SerializeObject(model);

                byte[] contentbyte = new byte[0];
                if (!string.IsNullOrEmpty(requestData))
                {
                    contentbyte = System.Text.Encoding.UTF8.GetBytes(requestData);
                }
                if (contentbyte.Length > 0)
                {
                    using (Stream contentStream = request.GetRequestStream())
                    {
                        contentStream.Write(contentbyte, 0, contentbyte.Length);
                        contentStream.Close();
                    }
                }
                #endregion

                #region RESPONSE
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string encoding = response.ContentEncoding;
                if (encoding == null || encoding.Length < 1)
                {
                    encoding = "UTF-8";
                }
                StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding(encoding));
                sret = reader.ReadToEnd();

                response.Close();
                #endregion

                return sret;
            }
            catch (WebException ex)
            {
                //记录错误
                throw;
            }
            catch (Exception ex)
            {
                //记录错误
                throw;
            }
            finally
            {
                //记录操作结果
            }
        }
        

   
        
    }

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

谁取了我的孔仔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值