Exemplo n.º 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);
            }
        }
Exemplo n.º 2
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);
        }
Exemplo n.º 3
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);
        }
Exemplo n.º 4
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);
        }
Exemplo n.º 5
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());
            }
        }
Exemplo n.º 6
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);
        }
Exemplo n.º 7
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();
            }
        }
Exemplo n.º 8
0
        /// <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);
            }
        }
Exemplo n.º 9
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("");
            }
        }
Exemplo n.º 10
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);
        }
Exemplo n.º 11
0
        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();
        }
Exemplo n.º 12
0
        /// <summary>
        /// Http方式下载文件
        /// </summary>
        /// <param name="url">http地址</param>
        /// <param name="localfile">本地文件</param>
        /// <returns></returns>
        public static bool Download(string url, string localfile)
        {
            bool       flag          = false;
            long       startPosition = 0;               // 上次下载的文件起始位置
            FileStream writeStream;                     // 写入本地文件流对象

            long remoteFileLength = GetHttpLength(url); // 取得远程文件长度

            System.Console.WriteLine("remoteFileLength=" + remoteFileLength);
            if (remoteFileLength == 745)
            {
                System.Console.WriteLine("远程文件不存在.");
                return(false);
            }

            // 判断要下载的文件夹是否存在
            if (File.Exists(localfile))
            {
                writeStream   = File.OpenWrite(localfile);           // 存在则打开要下载的文件
                startPosition = writeStream.Length;                  // 获取已经下载的长度

                if (startPosition >= remoteFileLength)
                {
                    System.Console.WriteLine("本地文件长度" + startPosition + "已经大于等于远程文件长度" + remoteFileLength);
                    writeStream.Close();

                    return(false);
                }
                else
                {
                    writeStream.Seek(startPosition, SeekOrigin.Current); // 本地文件写入位置定位
                }
            }
            else
            {
                QMLog qMLog = new QMLog();
                var   path  = localfile.Substring(0, localfile.LastIndexOf("\\"));
                if (Directory.Exists(path) == false)//如果不存在就创建file文件夹
                {
                    Directory.CreateDirectory(path);
                }
                writeStream   = new FileStream(localfile, FileMode.Create);// 文件不保存创建一个文件
                startPosition = 0;
            }


            try
            {
                HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(url);// 打开网络连接

                if (startPosition > 0)
                {
                    myRequest.AddRange((int)startPosition);// 设置Range值,与上面的writeStream.Seek用意相同,是为了定义远程文件读取位置
                }


                Stream readStream = myRequest.GetResponse().GetResponseStream();// 向服务器请求,获得服务器的回应数据流


                byte[] btArray     = new byte[512];                               // 定义一个字节数据,用来向readStream读取内容和向writeStream写入内容
                int    contentSize = readStream.Read(btArray, 0, btArray.Length); // 向远程文件读第一次

                long currPostion = startPosition;

                while (contentSize > 0)// 如果读取长度大于零则继续读
                {
                    currPostion += contentSize;
                    int percent = (int)(currPostion * 100 / remoteFileLength);
                    System.Console.WriteLine("percent=" + percent + "%");

                    writeStream.Write(btArray, 0, contentSize);                // 写入本地文件
                    contentSize = readStream.Read(btArray, 0, btArray.Length); // 继续向远程文件读取
                }

                //关闭流
                writeStream.Close();
                readStream.Close();

                flag = true;        //返回true下载成功
            }
            catch (Exception)
            {
                writeStream.Close();
                flag = false;       //返回false下载失败
            }

            return(flag);
        }
Exemplo n.º 13
0
        public static async Task <bool> DownTask()
        {
            QMLog qMLog = new QMLog();

            var _r = false;

            DbContextOptions <ContextString> options = new DbContextOptions <ContextString>();
            ContextString dbContext = new ContextString(options);

            var list = await dbContext.FileToBeDown.Where(i => i.StartNum < 10).OrderBy(o => o.StartNum).ToListAsync();

            if (list.Count() <= 0)
            {
                //文件已下载完毕
                _r = true;
                return(_r);
            }
            else
            {
                //取第一个任务
                var task = list.FirstOrDefault();

                var taskfile = await dbContext.AssetFiles.Where(i => i.Code == task.FileCode).FirstOrDefaultAsync();

                //文件无效
                if (taskfile == null)
                {
                    //删除记录
                    dbContext.FileToBeDown.Remove(task);
                    await dbContext.SaveChangesAsync();
                }
                else
                {
                    //下载文件
                    var suc = Download(Method.OSSServer + taskfile.FilePath, Method._hostingEnvironment.WebRootPath + taskfile.FilePath);

                    if (suc)
                    {
                        //下载成功 移除任务
                        dbContext.FileToBeDown.Remove(task);
                        await dbContext.SaveChangesAsync();
                    }
                    else
                    {
                        //下载失败
                        task.StartNum  += 1;
                        task.UpdateTime = DateTime.Now;
                        dbContext.FileToBeDown.Update(task);
                        await dbContext.SaveChangesAsync();
                    }
                }



                // 回调
                _r = await DownTask();

                //返回
                return(_r);
            }
        }