Beispiel #1
0
        public async Task mqttClientConnectAsync()
        {
            QMLog qMLog = new QMLog();

            var options = new MqttClientOptions
            {
                ClientId    = ClientId,
                Credentials = new MqttClientCredentials
                {
                    Username = Username,
                    Password = Password
                },
                ChannelOptions = new MqttClientTcpOptions
                {
                    Server = MqttServer,
                    Port   = MqttPort
                }
            };

            qMLog.WriteLogToFile("创建", JsonConvert.SerializeObject(options), 0);
            // qMLog.WriteLogToFile("MqttClientConnectAsync", JsonConvert.SerializeObject(options),0);
            try
            {
                await mqttClient.ConnectAsync(options);
            }
            catch (Exception e)
            {
                qMLog.WriteLogToFile("连接", e.ToString(), 0);
            }
        }
Beispiel #2
0
        /// <summary>
        /// 获取用户IP
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static string GetUserIp(HttpContext context)
        {
            var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
            //   var ip = context.Request.Headers["X-Original-For"].FirstOrDefault();
            QMLog qm = new QMLog();

            qm.WriteLogToFile("", ip);
            qm.WriteLogToFile("", context.Connection.RemoteIpAddress.ToString());
            if (string.IsNullOrEmpty(ip))
            {
                ip = context.Connection.RemoteIpAddress.ToString();
            }
            return(ip);
        }
Beispiel #3
0
        /// <summary>
        /// 删除文件记录及物理文件
        /// </summary>
        /// <param name="filepath"></param>
        /// <param name="dbContext"></param>
        /// <returns></returns>
        public static async Task <bool> DelFile(string Code, ContextString dbContext)
        {
            bool _Result = false;

            try
            {
                var file = await dbContext.AssetFiles.Where(i => i.Code == Code).AsNoTracking().FirstOrDefaultAsync();

                var           path = Method._hostingEnvironment.WebRootPath + file.FilePath;
                DirectoryInfo info = new DirectoryInfo(path);
                Directory.Delete(info.Parent.FullName, true);

                dbContext.AssetFiles.Remove(file);
                if (await dbContext.SaveChangesAsync() > 0)
                {
                    _Result = true;
                }
            }
            catch (Exception e)
            {
                QMLog qm = new QMLog();
                qm.WriteLogToFile("删除文件出错", e.ToString());
            }

            return(_Result);
        }
Beispiel #4
0
        public async Task PublishAsync(string ClientId, string reportedStr)
        {
            try
            {
                var jsonstr = "{\"reported\": " + reportedStr + "}";
                var appMsg  = new MqttApplicationMessage
                {
                    Topic   = "$baidu/iot/shadow/" + ClientId + "/update",
                    Payload = Encoding.UTF8.GetBytes(jsonstr),
                    QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce,
                    Retain = false
                };
                await mqttClient.PublishAsync(appMsg);
            }
            catch (Exception e)
            {
                //await mqttClientConnectAsync();
                //mqttClient.Connected += MqttClient_Connected;
                //mqttClient.Disconnected += MqttClient_Disconnected;

                //Sub();

                log.WriteLogToFile(e.Message, "mqtt");
            }
        }
Beispiel #5
0
        public async static Task <bool> ServerSubIOT()
        {
            DbContextOptions <ContextString> options = new DbContextOptions <ContextString>();
            ContextString dbContext = new ContextString(options);

            var serveriot = dbContext.ServerIOT.FirstOrDefault();

            ServerMqttClient mqttClient = new ServerMqttClient(Method.BaiduIOT, 1883, serveriot.ServerMac, serveriot.Name, serveriot.Key);

            mqttClient.InitAsync();

            mqttClient.Sub();

            var isStop = false;

            if (serveriot != null)
            {
                Thread thread = new Thread(new ThreadStart(() => {
                    while (!isStop)
                    {
                        Thread.Sleep(120000);


                        try
                        {
                            var jsonstr = "{\"reported\": " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "}";
                            //await mqttClient.PublishAsync(serveriot.ServerMac, jsonstr);
                            mqttClient.PublishAsync(serveriot.ServerMac, jsonstr);
                        }
                        catch (Exception ex)
                        {
                            QMLog qMLog = new QMLog();
                            qMLog.WriteLogToFile("", ex.ToString());
                        }
                        finally
                        {
                            Thread.Sleep(10000);
                        }
                    }
                }));
                thread.IsBackground = true;
                thread.Start();
            }



            return(true);
        }
Beispiel #6
0
        /// <summary>
        /// 更新服务器状态
        /// </summary>
        public static void UpdateDevState()
        {
            DateTime dt = DateTime.Now;

            try
            {
                QMLog qm = new QMLog();
                qm.WriteLogToFile("", "Hangfire定时器执行");
                DbContextOptions <ContextString> options = new DbContextOptions <ContextString>();
                ContextString dbContext = new ContextString(options);
                var           list      = dbContext.Device.ToList();
                foreach (var dev in list)
                {
                    var de = Method.DeviceCommandList.Where(i => i.Code == dev.Code).FirstOrDefault();
                    if (de == null)
                    {
                        dev.DeviceOnline = false;
                        dev.FrontOnline  = false;
                    }
                    else
                    {
                        if (de.DevBreathTime >= dt.AddMinutes(-1))
                        {
                            dev.DeviceOnline = true;
                        }
                        else
                        {
                            dev.DeviceOnline = false;
                        }
                        if (de.AppBreathTime >= dt.AddMinutes(-1))
                        {
                            dev.FrontOnline = true;
                        }
                        else
                        {
                            dev.FrontOnline = false;
                        }
                    }
                }
                dbContext.Device.UpdateRange(list);
                dbContext.SaveChanges();
            }
            catch (Exception e)
            {
                QMLog qm = new QMLog();
                qm.WriteLogToFile("", e.ToString());
            }
        }
Beispiel #7
0
        public async static Task <bool> ServerPublishIOT(ServerMqttClient mqttClient, ServerIOT serveriot)
        {
            var _r = true;

            try
            {
                var jsonstr = "{\"reported\": " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "}";
                await mqttClient.PublishAsync(serveriot.ServerMac, jsonstr);
            }
            catch (Exception ex)
            {
                QMLog qMLog = new QMLog();
                qMLog.WriteLogToFile("", "发送心跳包失败" + ex.ToString());
                _r = false;
            }



            return(_r);
        }
Beispiel #8
0
        public async void InitAsync()
        {
            QMLog qMLog = new QMLog();

            if (mqttClient == null)
            {
                qMLog.WriteLogToFile("创建", "调用初始化", 0);
                mqttClient = new MqttFactory().CreateMqttClient();



                if (!mqttClient.IsConnected)
                {
                    await mqttClientConnectAsync();
                }
                mqttClient.Connected    += MqttClient_Connected;
                mqttClient.Disconnected += MqttClient_Disconnected;

                // Sub();
            }
        }
        /// <summary>
        /// 接受消息
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="ct"></param>
        /// <returns></returns>
        private static async Task <string> ReceiveStringAsync(System.Net.WebSockets.WebSocket socket, CancellationToken ct = default(CancellationToken))
        {
            try
            {
                var buffer = new ArraySegment <byte>(new byte[1024]);
                using (var ms = new MemoryStream())
                {
                    WebSocketReceiveResult result;
                    do
                    {
                        ct.ThrowIfCancellationRequested();

                        result = await socket.ReceiveAsync(buffer, ct);



                        ms.Write(buffer.Array, buffer.Offset, result.Count);
                    }while (!result.EndOfMessage);

                    ms.Seek(0, SeekOrigin.Begin);
                    if (result.MessageType != WebSocketMessageType.Text)
                    {
                        return(null);
                    }

                    using (var reader = new StreamReader(ms, Encoding.UTF8))
                    {
                        return(await reader.ReadToEndAsync());
                    }
                }
            }
            catch (Exception)
            {
                QMLog qm = new QMLog();
                qm.WriteLogToFile("", "WebSocket断开");
                return(null);
            }
        }
Beispiel #10
0
        /// <summary>
        /// 获取文件MD5 哈希码
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string GetMD5HashFromFile(string fileName)
        {
            try
            {
                FileStream file = new FileStream(fileName, FileMode.Open);
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(file);
                file.Close();

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return(sb.ToString());
            }
            catch (Exception ex)
            {
                QMLog log = new QMLog();
                log.WriteLogToFile("GetMD5HashFromFile() fail, error:", ex.Message);
                return("");
            }
        }
Beispiel #11
0
        /// <summary>
        /// 下载一个远程文件(http方式)
        /// </summary>
        /// <param name="apppath">文件路径</param>
        /// <param name="filename">文件名称</param>
        /// <param name="dbContext">数据库连接字段</param>
        /// <returns></returns>
        public static async Task <long> DownloadFile(string apppath, ContextString dbContext)
        {
            QMLog qm      = new QMLog();
            long  _Result = -1;

            try
            {
                var    GUID     = Guid.NewGuid();
                string filename = apppath.Split('/').Last();
                var    client   = new HttpClient
                {
                    BaseAddress = new Uri(apppath)
                };

                var response = await client.GetAsync("");

                var stream = await response.Content.ReadAsStreamAsync();

                // var head = response.Headers;

                //声明字符数据,将获取到的流信息读到字符数组中
                byte[] byteArray = new byte[stream.Length];

                int readCount = 0; // 已经成功读取的字节的个数
                while (readCount < stream.Length)
                {
                    readCount += stream.Read(byteArray, readCount, (int)stream.Length - readCount);
                }



                AssetFile assetfile = new AssetFile();
                //文件名


                long filesize = stream.Length;
                //文件类型
                var ext = filename.Split('.').Last();


                FileTypeJudgment ftj = new FileTypeJudgment()
                {
                    TypeTarget = new TypeImg()
                };
                assetfile.FileType = "未知";
                if (ftj.Judge(ext))
                {
                    assetfile.FileType = "图片";
                }

                ftj.TypeTarget = new TypeVideo();
                if (ftj.Judge(ext))
                {
                    assetfile.FileType = "视频";
                }
                ftj.TypeTarget = new TypeApp();
                if (ftj.Judge(ext))
                {
                    assetfile.FileType = "应用";
                }



                //文件保存路径
                var    _FolderPath = @"\Files" + @"\" + GUID;
                string path        = Method._hostingEnvironment.WebRootPath + _FolderPath;

                if (Directory.Exists(path) == false)//如果不存在就创建file文件夹
                {
                    Directory.CreateDirectory(path);
                }

                //文件全路径
                var filepath = Method._hostingEnvironment.WebRootPath + _FolderPath + @"\" + filename;
                using (FileStream fs = System.IO.File.Create(filepath))
                {
                    fs.Write(byteArray, 0, (int)stream.Length);
                    fs.Flush();
                    fs.Dispose();
                }

                //添加文件到数据库

                assetfile.AddTime     = DateTime.Now;
                assetfile.FileExtName = ext;
                assetfile.Code        = GUID.ToString();
                assetfile.FileHash    = "";
                assetfile.FileName    = filename.Split('.').First();
                assetfile.FilePath    = @"\Files" + @"\" + GUID.ToString() + @"\" + filename;
                assetfile.FileSize    = filesize;
                dbContext.AssetFiles.Add(assetfile);

                if (dbContext.SaveChanges() > 0)
                {
                    _Result = assetfile.ID;
                }
                else
                {
                    qm.WriteLogToFile(filename, "添加文件到数据库失败");
                }
            }
            catch (Exception e)
            {
                qm.WriteLogToFile("", e.ToString());
            }


            return(_Result);
        }
        public async Task Invoke(HttpContext context)
        {
            //判断是否是WebSockets请求
            if (!context.WebSockets.IsWebSocketRequest)
            {
                await _next.Invoke(context);

                return;
            }

            //线程标志
            CancellationToken ct = context.RequestAborted;

            //当前连接
            var currentSocket = await context.WebSockets.AcceptWebSocketAsync();

            QMLog qMLog = new QMLog();

            qMLog.WriteLogToFile("socketId", context.Request.Query["Code"]);
            var socketId = context.Request.Query["Code"];

            if (string.IsNullOrEmpty(socketId))
            {
                return;
            }
            //获取客户端IP
            // var remoteIpAddress = context.Request.HttpContext.Connection.RemoteIpAddress;

            //将客户端IP作为标识符
            // string socketId = remoteIpAddress.ToString();

            //var ip = context.Request.Headers["X_REAL_IP"].FirstOrDefault();
            //if (string.IsNullOrEmpty(ip))
            //{
            //    ip = context.Connection.RemoteIpAddress.ToString();
            //}


            //将客户端IP作为标识符
            //string socketId = ip;



            //判断是否为已有连接,不是的话创建
            if (!_sockets.ContainsKey(socketId))
            {
                _sockets.TryAdd(socketId, currentSocket);
            }
            else
            {
                WebSocket socket;
                _sockets.TryGetValue(socketId, out socket);
                if (_sockets.TryRemove(socketId, out socket))
                {
                    qMLog.WriteLogToFile("添加socketId", context.Request.Query["Code"]);
                    _sockets.TryAdd(socketId, currentSocket);
                }
            }


            while (true)
            {
                if (ct.IsCancellationRequested)
                {
                    break;
                }

                string response = await ReceiveStringAsync(currentSocket, ct);

                if (response == null)
                {
                    break;
                }

                //MsgTemplate msg = JsonConvert.DeserializeObject<MsgTemplate>(response);

                if (string.IsNullOrEmpty(response))
                {
                    if (currentSocket.State != WebSocketState.Open)
                    {
                        break;
                    }

                    continue;
                }

                /*
                 * foreach (var socket in _sockets)
                 * {
                 *  if (socket.Value.State != WebSocketState.Open)
                 *  {
                 *      continue;
                 *  }
                 *   // 控制只有接收者才能收到消息
                 *  if (socket.Key == msg.ReceiverID || socket.Key == socketId)
                 *  {
                 *      await SendStringAsync(socket.Value, JsonConvert.SerializeObject(msg), ct);
                 *  }
                 * }
                 */
            }

            //_sockets.TryRemove(socketId, out dummy);

            await currentSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", ct);

            currentSocket.Dispose();
        }