wxr
2020-04-21 f718d23a262a5a8e1241fdeaeb4153399f95e79d
HDL_ON/DAL/Net/CommonPage.cs
@@ -1,7 +1,8 @@
using System;
using System.Text;
using HDL_ON.DAL.Net;
using HDL_ON.Entity.Enumerative;
using HDL_ON.Entity;
using HDL_ON.UI;
using Shared;
using Shared.Net;
@@ -11,47 +12,46 @@
    {
        public static bool IsRemote;
        //public static AirQuality AirQuality;
        public static Action RefreshAir;
        public static bool FindGateway = false;
        public static bool FindGatewayChilren = false;
        public static string FindGatewayChilrenIPAddress = new NetWiFi ().BroadcastIpAddress.ToString ();
        public static bool LocalPhoneFindDevice = false;
        public static string FindGatewayChilrenIPAddress = new NetWiFi().BroadcastIpAddress.ToString();
        private static string ip = "0.0.0.0";
        public static System.Net.IPEndPoint EndPoint {
            get {
                try {
                    if (FindGateway) {
                        return new System.Net.IPEndPoint (System.Net.IPAddress.Parse (new NetWiFi ().BroadcastIpAddress.ToString ()), 6000);
                    } else if (FindGatewayChilren) {
                        try {
                            return new System.Net.IPEndPoint (System.Net.IPAddress.Parse (FindGatewayChilrenIPAddress), 6000);
                        } catch {
                            return new System.Net.IPEndPoint (System.Net.IPAddress.Parse ("224.0.168.188"), 6000);
                        }
                    } else {
                        return new System.Net.IPEndPoint (System.Net.IPAddress.Parse (new NetWiFi ().BroadcastIpAddress.ToString ()), 6000);
                    }
                } catch {
        public static System.Net.IPEndPoint EndPoint
        {
            get
            {
                try
                {
                    return new System.Net.IPEndPoint(System.Net.IPAddress.Parse(new NetWiFi().BroadcastIpAddress.ToString()), 6000);
                }
                catch
                {
                    //防止异常导致程序退出
                    return new System.Net.IPEndPoint (System.Net.IPAddress.Parse ("127.0.0.1"), 6000);
                    return new System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), 6000);
                }
            }
        }
        ///保存设备备注才用gb2312,其他情况用utf8
        public static Encoding MyEncodingUTF8 = Encoding.UTF8;//Get
        public static Encoding MyEncodingGB2312 {
            get {
                try {
                    if (System.Globalization.CultureInfo.InstalledUICulture.EnglishName.ToUpper().StartsWith("CZECH")) {
                        return System.Text.Encoding.GetEncoding (1250);
                    } else {
                        return Encoding.GetEncoding ("gb2312");
        public static Encoding MyEncodingGB2312
        {
            get
            {
                try
                {
                    if (System.Globalization.CultureInfo.InstalledUICulture.EnglishName.ToUpper().StartsWith("CZECH"))
                    {
                        return Encoding.GetEncoding(1250);
                    }
                }catch (Exception ex) {
                    MainPage.Log ("MyEncodingGB2312 Erorr : "+ex.Message);
                    return Encoding.GetEncoding ("gb2312");
                    else
                    {
                        return Encoding.GetEncoding("gb2312");
                    }
                }
                catch (Exception ex)
                {
                    MainPage.Log("MyEncodingGB2312 Erorr : " + ex.Message);
                    return Encoding.GetEncoding("gb2312");
                }
            }
        }
@@ -59,136 +59,317 @@
        public static DateTime dt;
        //public static byte currentSubnetID = 0;
        public static void InitHttpListener ()
        public static void InitHttpListener()
        {
            if (isHttpListenerStart) {
            if (isHttpListenerStart)
            {
                return;
            }
            HttpListener.Start (new NetWiFi ().IpAddress, 6001);
            HttpListener.Start(new NetWiFi().IpAddress, 6001);
            HttpListener.EventHandler -= httpListener_EventHandler;
            HttpListener.EventHandler += httpListener_EventHandler;
            isHttpListenerStart = true;
        }
        public static void CloseHttpListener ()
        public static void CloseHttpListener()
        {
            //isHttpListenerStart = false;
            //return;
            if (!isHttpListenerStart)
                return;
            HttpListener.Close ();
            HttpListener.Close();
            isHttpListenerStart = false;
        }
        /// <summary>
        /// 初始化处理socket接收的数据 
        /// </summary>
        public static void InitReceiveEvent ()
        public static void InitReceiveEvent()
        {
            Packet.ReceiveEvent += Packet_ReceiveEvent;
        }
        public static float floatChange (byte b1, byte b2, byte b3, byte b4)
        public static float floatChange(byte b1, byte b2, byte b3, byte b4)
        {
            byte [] byteTemp = new byte [4] { b4, b3, b2, b1 };
            return BitConverter.ToSingle (byteTemp, 0);
            byte[] byteTemp = { b4, b3, b2, b1 };
            return BitConverter.ToSingle(byteTemp, 0);
        }
        static void Packet_ReceiveEvent (byte subnetID, byte deviceID, Command command, byte [] usefullBytes, string revGatewayIP)
        static void Packet_ReceiveEvent(byte subnetID, byte deviceID, Command command, byte[] receiveBytes, string revGatewayIP)
        {
            try
            {
                switch (command)
                {
                    case Command.ReadLightSingleLoopBrightnessACK:
                    case Command.SetSingleLightACK:
                        foreach (var function in DB_ResidenceData.residenceData.functionList.lights)
                        {
                            if (function.GetBusId() == subnetID + "_" + deviceID + "_" + receiveBytes[0])
                            {
                                if (function.functionCategory == FunctionCategory.Light&& function.functionType != FunctionType.RGB)
                                {
                                    var light = function as Light;
                                    //if (receiveBytes[2] == 0 && light.on_off == "off")
                                    //{
                                    //    break;
                                    //}
                                    //if (function.functionType == "Relay")
                                    //{
                                    //    var relay = function as Light;
                                    //    relay.on_off = receiveBytes[2] == 0 ? "off" : "on";
                                    //    HomePage.UpdataLightView(relay);
                                    //}
                                    //else if (function.functionType == "Dimmer")
                                    //{
                                    //var light = function as Light;
                                    light.on_off = receiveBytes[2] == 0 ? "off" : "on";
                                    if (light.on_off == "on")
                                    {
                                        light.brightness = receiveBytes[2];
                                        light.lastState = Language.StringByID(StringId.Brightness) + " : " + receiveBytes[2] + "%";
                                    }
                                    HomePage.UpdataFunctionStates(light);
                                    RoomPage.UpdataStates(light);
                                    FunctionPage.UpdataStates(light);
                                    ClassificationPage.UpdataInfo(light);
                                    switch (light.functionType)
                                    {
                                        case FunctionType.Relay:
                                            RelayPage.UpdataState(light);
                                            break;
                                        case FunctionType.Dimmer:
                                            DimmerPage.UpdataStates(light);
                                            break;
                                    }
                                    //}
                                }
                            }
                        }
                        break;
                    case Command.SetLogicLoopColorACK:
                    case Command.ReadLogicLoopColorACK:
                        foreach (var rgb in DB_ResidenceData.residenceData.functionList.lights)
                        {
                            if (rgb.GetBusId() == subnetID + "_" + deviceID + "_" + receiveBytes[0])
                            {
                                if (rgb.functionType == FunctionType.RGB)
                                {
                                    rgb.on_off = receiveBytes[1] > 0 ? "on" : "off";
                                    if (receiveBytes[1] >0)
                                    {
                                        rgb.brightness = receiveBytes[1];
                                        rgb.lastState = Language.StringByID(StringId.Brightness) + " : " + receiveBytes[1] + "%";
                                    }
                                    rgb.redColor = receiveBytes[6];
                                    rgb.greenColor = receiveBytes[7];
                                    rgb.blueColor = receiveBytes[8];
                                    HomePage.UpdataFunctionStates(rgb);
                                    RoomPage.UpdataStates(rgb);
                                    FunctionPage.UpdataStates(rgb);
                                    ClassificationPage.UpdataInfo(rgb);
                                    RGBPage.UpdataStates(rgb);
                                }
                            }
                        }
                        break;
                    case Command.SetCurtainModelStutasACK:
                    case Command.ReadCurtainStutasACK:
                        foreach (var curtain in DB_ResidenceData.residenceData.functionList.curtains)
                        {
                            if (curtain.GetBusId() == subnetID + "_" + deviceID + "_" + receiveBytes[0])
                            {
                                switch(receiveBytes[1])
                                {
                                    case 0:
                                        curtain.on_off = "stop";
                                        break;
                                    case 1:
                                        curtain.on_off = "on";
                                        curtain.lastState = Language.StringByID(StringId.Open);
                                        break;
                                    case 2:
                                        curtain.on_off = "off";
                                        curtain.lastState = Language.StringByID(StringId.Close);
                                        break;
                                    default:
                                        if (receiveBytes[1] > 1)
                                        {
                                            curtain.on_off = "on";
                                        }
                                        else
                                        {
                                            curtain.on_off = "off";
                                        }
                                        curtain.openLevel = receiveBytes[1];
                                        curtain.lastState = Language.StringByID(StringId.Open) + curtain.openLevel + "%";
                                        break;
                                }
                                RoomPage.UpdataStates(curtain);
                                FunctionPage.UpdataStates(curtain);
                                HomePage.UpdataFunctionStates(curtain);
                                ClassificationPage.UpdataInfo(curtain);
                                switch (curtain.functionType)
                                {
                                    case FunctionType.Curtain:
                                        CurtainModulePage.UpdataState(curtain);
                                        break;
                                }
                            }
                        }
                        break;
                    case Command.SetACModeACK:
                    case Command.ReadACModeACK:
                        foreach (var ac in DB_ResidenceData.residenceData.functionList.aCs)
                        {
                            if (ac.GetBusId() == subnetID + "_" + deviceID + "_" + receiveBytes[0])
                            {
                                ac.curTempType = receiveBytes[1];
                                ac.indoorTemp = receiveBytes[2];
                                ac.on_off = receiveBytes[8] == 1 ? "on" : "off";
                                ac.curModeIndex = receiveBytes[9];
                                ac.curFanIndex = receiveBytes[10];
                                ac.curTemp = receiveBytes[11];
                                ac.lastState = "";
                                switch (ac.curMode)
                                {
                                    case "cool":
                                        ac.lastState = Language.StringByID(StringId.Cool);
                                        break;
                                    case "heat":
                                        ac.lastState = Language.StringByID(StringId.Heat);
                                        break;
                                    case "dry":
                                        ac.lastState = Language.StringByID(StringId.Dry);
                                        break;
                                    case "auto":
                                        ac.lastState = Language.StringByID(StringId.Auto);
                                        break;
                                    case "fan":
                                        ac.lastState = Language.StringByID(StringId.AirSupply);
                                        break;
                                }
                                switch (ac.curFan)
                                {
                                    case "high":
                                        ac.lastState += " " + Language.StringByID(StringId.HighWindSpeed);
                                        break;
                                    case "medium":
                                        ac.lastState += " " + Language.StringByID(StringId.MiddleWindSpeed);
                                        break;
                                    case "low":
                                        ac.lastState += " " + Language.StringByID(StringId.LowWindSpeed);
                                        break;
                                    case "auto":
                                        ac.lastState += " " + Language.StringByID(StringId.Auto);
                                        break;
                                }
                                ac.lastState += " " + ac.curTemp + "°C";
                                RoomPage.UpdataStates(ac);
                                FunctionPage.UpdataStates(ac);
                                HomePage.UpdataFunctionStates(ac);
                                ClassificationPage.UpdataInfo(ac);
                                ACPage.UpdataStates(ac);
                            }
                        }
                        break;
                }
            }
            catch (Exception ex)
            {
                MainPage.Log($"Bus Rev Erorr : {ex.Message}");
            }
        }
        /// <summary>
        /// byte 变字符串
        /// </summary>
        /// <returns>The to hex16.</returns>
        /// <param name="b">The blue component.</param>
        public static string byteToHex16 (byte b)
        public static string byteToHex16(byte b)
        {
            string s = Convert.ToString (b, 16).ToUpper ();
            if (s.Length <= 1) {
            string s = Convert.ToString(b, 16).ToUpper();
            if (s.Length <= 1)
            {
                return "0" + s;
            }
            return s;//
        }
        static void httpListener_EventHandler (System.Collections.Specialized.NameValueCollection nameValueCollection, System.IO.Stream outputStream, System.IO.Stream inputStream)
        static void httpListener_EventHandler(System.Collections.Specialized.NameValueCollection nameValueCollection, System.IO.Stream outputStream, System.IO.Stream inputStream)
        {
            try {
                if (nameValueCollection ["Command"] != null && nameValueCollection ["Command"].StartsWith ("Get")) {
                    string tempFileName = nameValueCollection ["Command"].Replace ("Get", "");
                    if ("AllFiles" == tempFileName) {
                        byte [] bytes = System.Text.Encoding.UTF8.GetBytes (Newtonsoft.Json.JsonConvert.SerializeObject (MyIO.FileUtils.ReadFiles ()));
                        outputStream.Write (bytes, 0, bytes.Length);
                        outputStream.Flush ();
                    } else {
                        byte [] bytes;
                        if (!MyIO.FileUtils.Exists (tempFileName)) {
                            bytes = System.Text.Encoding.UTF8.GetBytes ("文件名不存在!");
                            outputStream.Write (bytes, 0, bytes.Length);
                            outputStream.Flush ();
            try
            {
                if (nameValueCollection["Command"] != null && nameValueCollection["Command"].StartsWith("Get"))
                {
                    string tempFileName = nameValueCollection["Command"].Replace("Get", "");
                    if ("AllFiles" == tempFileName)
                    {
                        byte[] bytes = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(FileUtils.ReadFiles()));
                        outputStream.Write(bytes, 0, bytes.Length);
                        outputStream.Flush();
                    }
                    else
                    {
                        byte[] bytes;
                        if (!FileUtils.Exists(tempFileName))
                        {
                            bytes = System.Text.Encoding.UTF8.GetBytes("文件名不存在!");
                            outputStream.Write(bytes, 0, bytes.Length);
                            outputStream.Flush();
                            return;
                        }
                        System.IO.FileStream fs = new System.IO.FileStream (Application.RootPath + tempFileName, System.IO.FileMode.Open);
                        bytes = new byte [fs.Length];
                        fs.Read (bytes, 0, bytes.Length);
                        fs.Close ();
                        outputStream.Write (bytes, 0, bytes.Length);
                        outputStream.Flush ();
                        System.IO.FileStream fs = new System.IO.FileStream(Application.RootPath + tempFileName, System.IO.FileMode.Open);
                        bytes = new byte[fs.Length];
                        fs.Read(bytes, 0, bytes.Length);
                        fs.Close();
                        outputStream.Write(bytes, 0, bytes.Length);
                        outputStream.Flush();
                    }
                } else if (nameValueCollection ["Command"].StartsWith ("Upload")) {
                    string path = Application.RootPath + nameValueCollection ["Command"].Replace ("Upload", "");
                    string dePath = nameValueCollection ["Command"].Replace ("Upload", "");
                } else {
                    byte [] bytes = System.Text.Encoding.UTF8.GetBytes ("请求命令无效!");
                    outputStream.Write (bytes, 0, bytes.Length);
                    outputStream.Flush ();
                }
            } catch (Exception ex) {
                MainPage.Log ("httpListener_EventHandler" + ex.ToString ());
                else if (nameValueCollection["Command"].StartsWith("Upload"))
                {
                    string path = Application.RootPath + nameValueCollection["Command"].Replace("Upload", "");
                    string dePath = nameValueCollection["Command"].Replace("Upload", "");
                }
                else
                {
                    byte[] bytes = System.Text.Encoding.UTF8.GetBytes("请求命令无效!");
                    outputStream.Write(bytes, 0, bytes.Length);
                    outputStream.Flush();
                }
            }
        }
        /// <summary>
        /// 随机数高位
        /// </summary>
        public static byte RandomHigh;
        /// <summary>
        /// 随机数低位
        /// </summary>
        public static byte RandomLow;
        /// <summary>
        /// Updates Device's remake.
        /// </summary>
        public static void UpdateRemark (byte subnetID, byte deviceID, string remark)
        {
            byte [] updateBytes = new byte [20];
            byte [] remakeBytes = MyEncodingGB2312.GetBytes (remark);
            Array.Copy (remakeBytes, 0, updateBytes, 0, remakeBytes.Length < 20 ? remakeBytes.Length : 20);
            Control.ControlBytesSend (Command.UpdataRemake, subnetID, deviceID, updateBytes);
            catch (Exception ex)
            {
                MainPage.Log("httpListener_EventHandler" + ex.ToString());
            }
        }
        /// <summary>
        /// 监听请求的Http端口
        /// </summary>
        public static int Port = 5555;
        static void httpListener_EventHandler (string rawUrl, System.IO.Stream outputStream, System.IO.Stream inputStream)
        static void httpListener_EventHandler(string rawUrl, System.IO.Stream outputStream, System.IO.Stream inputStream)
        {
            foreach (var musicInfo in MusicInfo.MusicInfoList) {
                if ("audio-item-" + musicInfo.ID == rawUrl.TrimStart ('/')) {
                    var file = new System.IO.FileStream (musicInfo.Data, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                    byte [] bytes = new byte [1024];
                    try {
                        while (file.CanRead) {
                            int len = file.Read (bytes, 0, bytes.Length);
                            if (len == 0) {
            foreach (var musicInfo in MusicInfo.MusicInfoList)
            {
                if ("audio-item-" + musicInfo.ID == rawUrl.TrimStart('/'))
                {
                    var file = new System.IO.FileStream(musicInfo.Data, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                    byte[] bytes = new byte[1024];
                    try
                    {
                        while (file.CanRead)
                        {
                            int len = file.Read(bytes, 0, bytes.Length);
                            if (len == 0)
                            {
                                break;
                            }
                            outputStream.Write (bytes, 0, len);
                            outputStream.Write(bytes, 0, len);
                        }
                    } catch { }
                    file.Close ();
                    }
                    catch { }
                    file.Close();
                    break;
                }
            }