Beispiel #1
0
        private bool  SetAllOutput()
        {
            byte[] writeOutputStatueBufferCopy = new byte[WriteOutputStatueBuffer.Length];
            lock (LockSetOutput)
            {
                if (CheckSame(lastWriteOutputStatueBuffer, WriteOutputStatueBuffer))
                {
                    return(true);
                }
                Array.Copy(WriteOutputStatueBuffer, writeOutputStatueBufferCopy, WriteOutputStatueBuffer.Length);
            }

            byte[] data = new byte[11];
            data[0] = (byte)CardIndex;
            data[1] = 0x10;
            data[2] = 0x80;
            data[3] = 0x50;
            data[4] = 0x00;
            data[5] = 0x02;
            data[6] = 0x04;

            data[7] = writeOutputStatueBufferCopy[1];
            data[8] = writeOutputStatueBufferCopy[0];
            byte[] senddata = new byte[data.Length + 2];

            CRC.CRC16(data, CrcPloy, ref senddata[data.Length + 1], ref senddata[data.Length]);

            data.CopyTo(senddata, 0);
            port.Write(senddata, 0, senddata.Length);

            //校验返回数据
            Thread.Sleep(50);
            int count = port.BytesToRead;

            byte[] rtnData = new byte[count];
            port.Read(rtnData, 0, count);
            int startIndex = 0;

            byte[] retDataHead = new byte[] { (byte)CardIndex, 0x10, 0x80, 0x50 };
            if (!CheckContains(rtnData, retDataHead, ref startIndex))
            {
                return(false);
            }
            byte[] useInfo = new byte[6];
            Array.Copy(rtnData, startIndex, useInfo, 0, useInfo.Length);
            byte crcH = 0;
            byte crcL = 0;

            CRC.CRC16(useInfo, CrcPloy, ref crcL, ref crcH);
            if (crcL != rtnData[startIndex + useInfo.Length + 1] || crcH != rtnData[startIndex + useInfo.Length])
            {
                return(false);
            }
            lock (LockReadOutput)
            {
                Array.Copy(writeOutputStatueBufferCopy, lastWriteOutputStatueBuffer, WriteOutputStatueBuffer.Length);
            }
            return(true);
        }
Beispiel #2
0
        public void CRCTest()
        {
            byte[] bytes = new byte[sizeof(int)];
            Int16  crc16 = CRC.CRC16(bytes);
            Int32  crc32 = CRC.CRC32(bytes);

            _logger.Debug("CRC", crc16.ToString("X2"));
            _logger.Debug("CRC", crc32.ToString("X2"));
        }
Beispiel #3
0
        private void GetAllInputStatue()
        {
            byte[] data = new byte[6];
            data[0] = (byte)CardIndex;
            data[1] = 0x03;
            data[2] = 0x80;
            data[3] = 0x40;
            data[4] = 0x00;
            data[5] = 0x02;

            byte[] senddata = new byte[8];

            CRC.CRC16(data, CrcPloy, ref senddata[7], ref senddata[6]);

            data.CopyTo(senddata, 0);
            port.Write(senddata, 0, senddata.Length);
            Thread.Sleep(50);
            int count = port.BytesToRead;

            byte[] rtnData = new byte[count];
            port.Read(rtnData, 0, count);

            int startIndex = 0;

            byte[] retDataHead = new byte[] { (byte)CardIndex, 0x03, 0x04 };
            if (!CheckContains(rtnData, retDataHead, ref startIndex))
            {
                return;
            }
            byte[] useInfo = new byte[7];
            Array.Copy(rtnData, startIndex, useInfo, 0, useInfo.Length);
            byte crcH = 0;
            byte crcL = 0;

            CRC.CRC16(useInfo, CrcPloy, ref crcL, ref crcH);
            if (crcL != rtnData[startIndex + useInfo.Length + 1] || crcH != rtnData[startIndex + useInfo.Length])
            {
                return;
            }
            lock (LockReadInput)
            {
                inputStatueBuffer[0] = rtnData[startIndex + 6];
                inputStatueBuffer[1] = rtnData[startIndex + 5];
            }

            if (CheckSame(lastInputStatueBuffer, inputStatueBuffer))
            {
                return;
            }
            //可触发事件
            inputStatueBuffer.CopyTo(lastInputStatueBuffer, 0);
        }
Beispiel #4
0
        /// <summary>
        /// Send data over bluetooth serial
        /// </summary>
        /// <param name="dataToSend"></param>
        /// <returns></returns>
        public bool SendData(byte[] data)
        {
            lock (channelLock) {
                ushort crcno    = CRC.CRC16(data, 0, data.Length);
                Byte[] crcbytes = BitConverter.GetBytes(crcno);

                bt.Write(crcbytes, 0, crcbytes.Length);
                bt.Write(data, 0, data.Length);

                Util.Delay(200);
            }
            return(true);
        }
Beispiel #5
0
        /// <summary>
        /// Send data over bluetooth serial
        /// </summary>
        /// <param name="dataToSend"></param>
        /// <returns></returns>
        public bool SendData(string dataToSend)
        {
            lock (channelLock) {
                byte[] data = StringToByteArray(dataToSend);

                ushort crcno    = CRC.CRC16(data, 0, data.Length);
                Byte[] crcbytes = BitConverter.GetBytes(crcno);

                bt.Write(crcbytes, 0, crcbytes.Length);
                bt.Write(data, 0, dataToSend.Length);

                Util.Delay(200);
            }
            return(true);
        }
Beispiel #6
0
        void bt_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            ushort passedCrc;
            ushort crcno;
            bool   valid = false;
            int    bytesRead;

            Util.Delay(100);

            lock (channelLock) {
                //byte[] buffer = new byte[bt.BytesToRead];



                if (bt.BytesToRead == 0)
                {
                    return;
                }
                bytesRead = bt.BytesToRead > 1024 ? 1024 : bt.BytesToRead;

                bt.Read(buffer, 0, bytesRead);

                Debug.Print(ToString(buffer));

                if (bytesRead < 2)
                {
                    passedCrc = 1;
                    crcno     = 0;
                }
                else
                {
                    crcno     = CRC.CRC16(buffer, 2, bytesRead);
                    passedCrc = BitConverter.ToUInt16(buffer, 0);
                }

                if (crcno != passedCrc)
                {
                    valid = false;
                }
                else
                {
                    valid = true;
                }

                OnChanged(new DataRecievedEventArgs(BytesToString(buffer), valid, crcno));
            }
        }
        static string FormatCSProtos(List <ProtoCell> lProtos, string csfile)
        {
            Console.WriteLine($"generating csfile {csfile}");
            string sproto = "using System.Collections.Generic;"
                            + "\n" + "using System.IO;"
                            + "\n\n" + "namespace LibPacket"
                            + "\n{";

            foreach (ProtoCell cell in lProtos)
            {
                sproto += "\n\tpublic class " + cell.pktName + " : PktBase//" + CRC.CRC16(cell.pktName)
                          + "\n\t{"
                ;
                int i = 0;
                foreach (string senum in cell.lEnumLines)
                {
                    sproto += "\n\t\t";
                    if (i == 0)
                    {
                        sproto += "public ";
                    }
                    else if (i != 1 && i != cell.lEnumLines.Count - 1)
                    {
                        sproto += "\t";
                    }
                    sproto += senum.Replace(";", ",");
                    i++;
                }

                var sserialize   = "";
                var sdeserialize = "";
                foreach (ProtoParamCell ppc in cell.lParams)
                {
                    if (string.IsNullOrEmpty(sserialize))
                    {
                        sserialize = "\n\t\t\tthis.stream = ms;";
                    }
                    if (string.IsNullOrEmpty(sdeserialize))
                    {
                        sdeserialize = "\n\t\t\tthis.stream = ms;" +
                                       "\n\t\t\tvar tag = 0;" +
                                       "\n\t\t\twhile (reader.BaseStream.Position < reader.BaseStream.Length && (tag = reader.ReadInt32()) != 0)" +
                                       "\n\t\t\t{" +
                                       "\n\t\t\t\tswitch (tag)" +
                                       "\n\t\t\t\t{"
                        ;
                    }
                    string sparam = "\n\t\t" + "private " + ppc.paramType + " _" + ppc.paramName;
                    sdeserialize += $"\n\t\t\t\t\tcase {ppc.paramIndex}:"
                                    + "\n\t\t\t\t\t\t{";
                    if (sparam.IndexOf("List") != -1)
                    {
                        sparam     += " = new " + ppc.paramType + "();";
                        sserialize += $"\n\t\t\tif ({ppc.paramName}.Count > 0)" +
                                      "\n\t\t\t{" +
                                      $"\n\t\t\t\twriter.Write({ppc.paramIndex});" +
                                      $"\n\t\t\t\twriter.Write({ppc.paramName}.Count);" +
                                      $"\n\t\t\t\tforeach (var __item in {ppc.paramName})" +
                                      "\n\t\t\t\t{"
                        ;
                        sdeserialize += "\n\t\t\t\t\t\t\tvar count = reader.ReadInt32();" +
                                        "\n\t\t\t\t\t\t\tfor (var i = 0; i < count; i++)" +
                                        "\n\t\t\t\t\t\t\t{";
                        var t = ppc.paramType.Substring(5, ppc.paramType.Length - 6);
                        if (lProtoNames.Contains(t))
                        {
                            sserialize += "\n\t\t\t\t\tvar m = new MemoryStream();"
                                          + "\n\t\t\t\t\t__item.Serialize(m);"
                                          + "\n\t\t\t\t\tvar bs = m.ToArray();"
                                          + "\n\t\t\t\t\twriter.Write(bs.Length);"
                                          + "\n\t\t\t\t\twriter.Write(bs);";
                            sdeserialize += $"\n\t\t\t\t\t\t\t\tvar __item = new {t}();"
                                            + "\n\t\t\t\t\t\t\t\tvar c = reader.ReadInt32();"
                                            + $"\n\t\t\t\t\t\t\t\t__item.Deserialize(new MemoryStream(reader.ReadBytes(c)));"
                            ;
                        }
                        else
                        {
                            sserialize   += $"\n\t\t\t\t\twriter.Write(__item);";
                            sdeserialize += $"\n\t\t\t\t\t\t\t\tvar __item = reader.Read{GetReaderSuffix(t)}();";
                        }
                        sserialize += "\n\t\t\t\t}"
                                      + "\n\t\t\t}";
                        sdeserialize += $"\n\t\t\t\t\t\t\t\t{ppc.paramName}.Add(__item);"
                                        + "\n\t\t\t\t\t\t\t}";
                    }
                    else if (lProtoNames.Contains(ppc.paramType))
                    {
                        sparam     += " = null;";
                        sserialize += $"\n\t\t\tif ({ppc.paramName} != null)" +
                                      "\n\t\t\t{" +
                                      $"\n\t\t\t\twriter.Write({ppc.paramIndex});" +
                                      "\n\t\t\t\tvar m = new MemoryStream();" +
                                      $"\n\t\t\t\t{ppc.paramName}.Serialize(m);" +
                                      "\n\t\t\t\tvar bs = m.ToArray();" +
                                      "\n\t\t\t\twriter.Write(bs.Length);" +
                                      "\n\t\t\t\twriter.Write(bs);" +
                                      "\n\t\t\t}"
                        ;
                        sdeserialize += $"\n\t\t\t\t\t\t\t{ppc.paramName} = new {ppc.paramType}();"
                                        + "\n\t\t\t\t\t\t\tvar c = reader.ReadInt32();"
                                        + $"\n\t\t\t\t\t\t\t{ppc.paramName}.Deserialize(new MemoryStream(reader.ReadBytes(c)));"
                        ;
                    }
                    else if (ppc.paramType.ToLower() == "string")
                    {
                        sparam     += " = \"\";";
                        sserialize += $"\n\t\t\tif (!string.IsNullOrEmpty({ppc.paramName}))" +
                                      "\n\t\t\t{" +
                                      $"\n\t\t\t\twriter.Write({ppc.paramIndex});" +
                                      $"\n\t\t\t\twriter.Write({ppc.paramName});" +
                                      "\n\t\t\t}"
                        ;
                        sdeserialize += $"\n\t\t\t\t\t\t\t{ppc.paramName} = reader.Read{GetReaderSuffix(ppc.paramType)}();";
                    }
                    else if (ppc.paramType == "bool")
                    {
                        sparam     += " = false;";
                        sserialize += $"\n\t\t\tif ({ppc.paramName})" +
                                      "\n\t\t\t{" +
                                      $"\n\t\t\t\twriter.Write({ppc.paramIndex});" +
                                      $"\n\t\t\t\twriter.Write({ppc.paramName});" +
                                      "\n\t\t\t}"
                        ;
                        sdeserialize += $"\n\t\t\t\t\t\t\t{ppc.paramName} = reader.Read{GetReaderSuffix(ppc.paramType)}();";
                    }
                    else
                    {
                        sparam += " = default(" + ppc.paramType + ");";
                        if (lEnumNames.Contains(ppc.paramType) || ppc.paramType.Contains("."))
                        {
                            sserialize += $"\n\t\t\tif ({ppc.paramName} != 0)" +
                                          "\n\t\t\t{" +
                                          $"\n\t\t\t\twriter.Write({ppc.paramIndex});" +
                                          $"\n\t\t\t\twriter.Write((int){ppc.paramName});" +
                                          "\n\t\t\t}"
                            ;
                            sdeserialize += $"\n\t\t\t\t\t\t\t{ppc.paramName} = ({ppc.paramType})reader.ReadInt32();";
                        }
                        else
                        {
                            sserialize += $"\n\t\t\tif ({ppc.paramName} != 0)" +
                                          "\n\t\t\t{" +
                                          $"\n\t\t\t\twriter.Write({ppc.paramIndex});" +
                                          $"\n\t\t\t\twriter.Write({ppc.paramName});" +
                                          "\n\t\t\t}"
                            ;
                            sdeserialize += $"\n\t\t\t\t\t\t\t{ppc.paramName} = reader.Read{GetReaderSuffix(ppc.paramType)}();";
                        }
                    }
                    sdeserialize += "\n\t\t\t\t\t\t\tbreak;"
                                    + "\n\t\t\t\t\t\t}";
                    sparam += "\n\t\t" + "public " + ppc.paramType + " " + ppc.paramName
                              + "\n\t\t" + "{"
                              + "\n\t\t\t" + "get { " + "return _" + ppc.paramName + "; }"
                              + "\n\t\t\t" + "set { " + "_" + ppc.paramName + " = value; }"
                              + "\n\t\t" + "}";
                    sproto += sparam;
                    sproto += "\n";
                }

                if (!string.IsNullOrEmpty(sdeserialize))
                {
                    sdeserialize += "\n\t\t\t\t}" +
                                    "\n\t\t\t}";
                }
                sproto += "\n\t\tpublic override void Serialize(MemoryStream ms)" +
                          "\n\t\t{" +
                          sserialize +
                          "\n\t\t}" +
                          "\n\t\tpublic override void Deserialize(MemoryStream ms)" +
                          "\n\t\t{" +
                          sdeserialize +
                          "\n\t\t}"
                ;
                sproto += "\n\t}\n";
            }
            sproto += "\n}";

            StreamWriter sw = new StreamWriter(csfile);

            sw.Write(sproto);
            sw.Close();

            return(sproto);
        }
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                printHelp();
                End();
                return;
            }
            Dictionary <string, string> dInfos = new Dictionary <string, string>();

            foreach (string sarg in args)
            {
                string[] aarg = sarg.Split(new string[] { ":" }, 2, StringSplitOptions.RemoveEmptyEntries);
                if (aarg.Length < 2)
                {
                    continue;
                }
                if (!dInfos.ContainsKey(aarg[0]))
                {
                    dInfos.Add(aarg[0], aarg[1]);
                }
            }
            if (dInfos.ContainsKey("debug"))
            {
                Debugger.Launch();
            }
            if (!dInfos.ContainsKey("file") || !dInfos.ContainsKey("out-cs"))
            {
                printHelp();
                End();
                return;
            }
            string sreadfile = FormatPath(dInfos["file"]);

            if (!File.Exists(sreadfile))
            {
                Console.WriteLine("找不到文件" + sreadfile);
                End();
                return;
            }

            List <ProtoCell> lProtoCells = new List <ProtoCell>();
            bool             bHasError   = false;

            StreamReader sr           = new StreamReader(sreadfile);
            int          lineNum      = 0;
            string       line         = null;
            ProtoCell    curProtoCell = new ProtoCell();
            bool         bLeftDet     = false;
            bool         bRightDet    = true;

            while ((line = sr.ReadLine()) != null)
            {
                lineNum++;
                line = line.Trim();
                if (string.IsNullOrEmpty(line))
                {
                    continue;
                }

                if (!curProtoCell.bBegan)
                {
                    if (!bRightDet)
                    {
                        bHasError = true;
                        LineError(lineNum, "期待一个单独的'}'符号");
                        break;
                    }

                    string[] aline = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    if (aline[0] == "message")
                    {
                        if (aline.Length < 2)
                        {
                            bHasError = true;
                            LineError(lineNum, "没有找到协议名");
                            break;
                        }
                        if (lProtoNames.Contains(aline[1]))
                        {
                            bHasError = true;
                            LineError(lineNum, "重复的协议名" + aline[1]);
                            break;
                        }
                        curProtoCell.pktName = aline[1];
                        lProtoNames.Add(curProtoCell.pktName);
                        curProtoCell.id = CRC.CRC16(curProtoCell.pktName);
                        lProtoCells.Add(curProtoCell);
                        dProtoIDs.Add(curProtoCell.pktName, curProtoCell.id);
                        curProtoCell.bBegan = true;
                    }
                    else if (aline[0] == "enum")
                    {
                        bHasError = true;
                        LineError(lineNum, "枚举只能定义到message内部,暂不支持message外部的枚举" + line);
                        break;
                    }
                    else
                    {
                        bHasError = true;
                        LineError(lineNum, "找不到message关键字:" + line);
                        break;
                    }
                }
                else if (!bLeftDet)
                {
                    if (line == "{")
                    {
                        bLeftDet  = true;
                        bRightDet = false;
                    }
                    else
                    {
                        bHasError = true;
                        LineError(lineNum, "期待一个单独的'{'符号");
                        break;
                    }
                }
                else
                {
                    if (line == "}")
                    {
                        if (curProtoCell.bEnumBegin)
                        {
                            curProtoCell.AddEnum(line);
                            curProtoCell.bEnumBegin = false;
                        }
                        else
                        {
                            bRightDet    = true;
                            curProtoCell = new ProtoCell();
                            bLeftDet     = false;
                        }
                        continue;
                    }
                    else
                    {
                        string[] aline = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                        if (aline[0] == "enum" || curProtoCell.bEnumBegin)
                        {
                            if (aline[0] == "}")
                            {
                                curProtoCell.AddEnum(line.Trim());
                                curProtoCell.bEnumBegin = false;
                            }
                            else
                            {
                                if (aline[0] == "enum")
                                {
                                    lEnumNames.Add(aline[1]);
                                }
                                curProtoCell.bEnumBegin = true;
                                curProtoCell.AddEnum(line.Trim());
                            }
                        }
                        else
                        {
                            if (line.IndexOf(";") != line.Length - 1)
                            {
                                bHasError = true;
                                LineError(lineNum, "需要以;结尾");
                                break;
                            }
                            line = line.Substring(0, line.Length - 1);

                            aline = line.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                            if (aline.Length == 1)
                            {
                                bHasError = true;
                                LineError(lineNum, "找不到=");
                                break;
                            }

                            string[] aparam = aline[0].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                            if (aparam.Length != 2)
                            {
                                bHasError = true;
                                LineError(lineNum, "错误的属性");
                                break;
                            }
                            int paramIndex = 0;
                            int.TryParse(aline[1], out paramIndex);
                            string serror = curProtoCell.AddParam(aparam[0], aparam[1], paramIndex);
                            if (serror != null)
                            {
                                bHasError = true;
                                LineError(lineNum, serror);
                                break;
                            }
                        }
                    }
                }
            }
            sr.Close();

            if (!bHasError)
            {
                string csfile = FormatPath(dInfos["out-cs"]);
                if (csfile.LastIndexOf(".cs") != csfile.Length - 3)
                {
                    Console.WriteLine(csfile + " 不是一个合法的cs脚本");
                    End();
                    return;
                }

                FormatCSProtos(lProtoCells, csfile);
            }
        }
Beispiel #9
0
 public static int GetPktDef(Type pktType)
 {
     return(CRC.CRC16(pktType.FullName));
 }
Beispiel #10
0
        /// <summary>
        /// 命令反馈
        /// </summary>
        public bool GetCallBack()
        {
            try
            {
                int    offlinecount     = 0;
                int    allheadleftlengh = 3;
                int    receivedlengh    = 0;
                byte[] bufferhead       = new byte[3];
                while (allheadleftlengh - receivedlengh > 0)
                {
                    byte[] buffertemp = new byte[allheadleftlengh - receivedlengh];
                    if (Tcpsocket.Available <= 0)
                    {
                        continue;
                    }
                    int lengh = Tcpsocket.Receive(buffertemp);
                    if (lengh <= 0)
                    {
                        if (offlinecount == 3)
                        {
                            LogHelper.WriteReciveChargeMessLog("接受的充电桩" + DeviceID.ToString() + "反馈命令超时");
                            return(false);
                        }
                        offlinecount += 1;
                        Thread.Sleep(50);
                    }
                    Buffer.BlockCopy(buffertemp, 0, bufferhead, receivedlengh, lengh);
                    receivedlengh += lengh;
                }
                if (bufferhead[0] == 0x01 && bufferhead[1] == 0x01)
                {
                    offlinecount  = 0;
                    receivedlengh = 0;
                    int    allcontentleftlengh = Convert.ToInt32(bufferhead[2]) + 2;
                    byte[] buffercontent       = new byte[allcontentleftlengh];
                    while (allcontentleftlengh - receivedlengh > 0)
                    {
                        byte[] buffertemp = new byte[allcontentleftlengh - receivedlengh];
                        if (Tcpsocket.Available <= 0)
                        {
                            continue;
                        }
                        int lengh = Tcpsocket.Receive(buffertemp);
                        if (lengh <= 0)
                        {
                            if (offlinecount == 3)
                            {
                                LogHelper.WriteReciveChargeMessLog("接受的充电桩" + DeviceID.ToString() + "反馈命令超时");
                                return(false);
                            }
                            offlinecount += 1;
                            Thread.Sleep(50);
                        }
                        Buffer.BlockCopy(buffertemp, 0, buffercontent, receivedlengh, lengh);
                        receivedlengh += lengh;
                    }
                    List <byte> msg     = new List <byte>();
                    string      SenDLog = "";
                    msg.AddRange(bufferhead);
                    msg.AddRange(buffercontent);
                    foreach (byte item in msg)
                    {
                        SenDLog += ((int)item).ToString("X") + " ";
                    }
                    LogHelper.WriteReciveChargeMessLog("接受的充电桩" + this.DeviceID.ToString() + "反馈命令:" + SenDLog);


                    //List<byte> dd = new List<byte>();
                    //dd.AddRange(new byte[] { 0x01, 0x01, 0x03, 0x06, 0x01, 0x01, 0x1C, 0x1F });
                    //var rr = BitConverter.GetBytes(CRC.CRC16(dd.Take(dd.Count - 2).ToArray(), 0, dd.Count - 3));


                    var r = BitConverter.GetBytes(CRC.CRC16(msg.Take(msg.Count - 2).ToArray(), 0, msg.Count - 3));
                    if (msg[msg.Count - 2] != r[1] || msg[msg.Count - 1] != r[0])
                    {
                        LogHelper.WriteReciveChargeMessLog("接受的充电桩" + this.DeviceID.ToString() + "校验位错误!");
                        return(false);
                    }


                    //分析充电桩状态 0待机 1故障 2进行 3完成
                    ChargeStationInfo chargestation = new ChargeStationInfo();
                    chargestation.ID = this.DeviceID;
                    string StateStr = Convert.ToString(msg[3], 2).PadLeft(8, '0');
                    if (StateStr.Substring(7, 1) == "1")
                    {
                        chargestation.ChargeState = 0;
                    }
                    else if (StateStr.Substring(6, 1) == "1")
                    {
                        chargestation.ChargeState = 1;
                    }
                    else if (StateStr.Substring(5, 1) == "1")
                    {
                        chargestation.ChargeState = 2;
                    }
                    else if (StateStr.Substring(4, 1) == "1")
                    {
                        chargestation.ChargeState = 3;
                    }
                    else
                    {
                        chargestation.ChargeState = -1;
                    }
                    chargestation.IsCommBreak = false;
                    DelegateState.InvokeChargeChangeEvent(chargestation);
                    LastRecTime = DateTime.Now;
                    return(true);
                }
                else if (bufferhead[0] == 0x01 && bufferhead[1] == 0x05)
                {
                    return(true);
                }
                return(false);
            }
            catch (Exception ex)
            { LogHelper.WriteLog("充电桩解析编解码错误!" + ex.Message); }
            return(false);
        }
Beispiel #11
0
        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            if (!getdtulist())
            {
                MessageBox.Show("集中器离线");
                return;
            }
            var collectorNo = txt_Collector.Text.Trim();

            try
            {
                openFileDialog1.Filter          = "bin文件|*.bin";
                openFileDialog1.FilterIndex     = 0;
                openFileDialog1.CheckFileExists = true;
                openFileDialog1.CheckPathExists = true;
                openFileDialog1.Title           = "请选择上传的代码文件";
                openFileDialog1.Multiselect     = false;
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    FileInfo fi    = new FileInfo(openFileDialog1.FileName);
                    long     _size = fi.Length;//得到文件的字节大小
                    if (_size > 1024 * 100)
                    {
                        MessageBox.Show("文件不能大于100K");
                    }

                    using (var sr = fi.OpenText())
                    {
                        string restOfStream = sr.ReadToEnd();
                        if (restOfStream.Contains("6009*Boot"))
                        {
                            MessageBox.Show("文件包含有boot在里面,不能升级");

                            return;
                        }
                        //var m = Regex.Match(restOfStream, @"SRWF-\d{4}-[a-zA-Z]{1,4}-\d{8}-Vsp\d{1}.\d{2}");
                        var m = Regex.Match(restOfStream, @"SRWF-CTP-PARKING-\d{8}-Vsp\d{1}.\d{2}");
                        if (m.Success)
                        {
                            lblVersionInfo.Text = m.Value;
                        }
                        else
                        {
                            MessageBox.Show("文件不能读取版本信息");

                            return;
                        }
                    }
                    lblFileName.Text = fi.Name;
                    byte[] buffer = new byte[fi.Length];
                    using (var fs = fi.OpenRead())
                    {
                        fs.Read(buffer, 0, (int)fi.Length);
                    }

                    Logger.Instance.Info("开始上传。。。");
                    //lbxMemo.Items.Add();

                    long max = fi.Length % 200 == 0 ? fi.Length / 200 : fi.Length / 200 + 1;
                    pb_upgrade.Maximum = (int)max;

                    //开始上传文件
                    var crc16 = CRC.CRC16(buffer, 0, (int)fi.Length);

                    UInt32 currentPackageOffset = 0;
                    UInt16 currentPackageLen    = 0;
                    UInt16 totalLen             = (UInt16)fi.Length;
                    int    upgradeCount         = 0;

                    Task.Factory.StartNew(() => {
                        this.Invoke((EventHandler)(delegate
                        {
                            btnOpenFile.Enabled = false;
                        }));
                        while (totalLen > 0)
                        {
                            if (totalLen <= 200)
                            {
                                currentPackageLen = totalLen;
                                totalLen          = 0;
                            }
                            else
                            {
                                currentPackageLen = 200;
                                totalLen         -= 200;
                            }

                            var reqInfo = new CollectorUpgrade
                            {
                                FILE_CRC16  = crc16,
                                FILE_OFFSET = currentPackageOffset,
                                FILE_LEN    = (uint)fi.Length,
                                CODE_LEN    = currentPackageLen,
                                UserName    = "******",
                                Pass        = "******",
                                CollectorNo = collectorNo,
                            };
                            reqInfo.CODE_CONTENT = new Byte[currentPackageLen];
                            Array.Copy(buffer, currentPackageOffset, reqInfo.CODE_CONTENT, 0, currentPackageLen);

                            CollectorUpgrade resInfo = null;
                            for (int i = 0; i < 3; i++)
                            {
                                resInfo = upgradeFileCode(reqInfo);
                                if (resInfo.RESULT == 0xAA)
                                {
                                    break;
                                }
                            }
                            if (resInfo.RESULT == 0xAA)
                            {
                                currentPackageOffset += currentPackageLen;
                                this.Invoke((EventHandler)(delegate
                                {
                                    pb_upgrade.Value = ++upgradeCount;
                                    lbl_packageCount.Text = upgradeCount + "/" + max;
                                }));
                            }
                            else
                            {
                                MessageBox.Show("上传失败");
                                this.Invoke((EventHandler)(delegate
                                {
                                    pb_upgrade.Value = 0;
                                    btnOpenFile.Enabled = true;
                                    Logger.Instance.Error("上传失败");
                                }));

                                return;
                            }
                        }
                        MessageBox.Show("上传成功");
                        this.Invoke((EventHandler)(delegate
                        {
                            btnOpenFile.Enabled = true;
                            Logger.Instance.Info("上传成功");
                        }));
                    });
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("上传代码文件出错: " + ex.Message);

                btnOpenFile.Enabled = true;
                Logger.Instance.Error(ex.Message);

                pb_upgrade.Value = 0;
            }
        }
Beispiel #12
0
    public override int GetSign()
    {
        var sign = CRC.CRC16(typeof(T).Name);

        return(sign);
    }
Beispiel #13
0
 public override int GetSign()
 {
     return(CRC.CRC16(typeof(T).FullName));
 }