Beispiel #1
0
 //////////////////////////////////////////////////////////////////////
 public bool Write2DB(MySqlCommand cmd)     //запись в БД
 {
     try
     {
         cmd.Parameters["?ID"].Value      = m_ID;
         cmd.Parameters["?Time"].Value    = m_Time;
         cmd.Parameters["?Lat"].Value     = m_fLat;
         cmd.Parameters["?Lng"].Value     = m_fLng;
         cmd.Parameters["?Alt"].Value     = m_Alt;
         cmd.Parameters["?GSMInfo"].Value = m_ulMNID;
         cmd.Parameters["?Speed"].Value   = m_Speed;
         cmd.Parameters["?Status"].Value  = m_Status;
         cmd.Parameters["?IO"].Value      = GetIOBuffer();
         if (cmd.CommandText.ToLower().Contains("insert"))
         {
             cmd.Parameters["?ForwardTime"].Value  = 0;
             cmd.Parameters["?ReceivedTime"].Value = CTime.GetTime(DateTime.UtcNow);
         }
         cmd.ExecuteNonQuery();
     }
     catch (Exception ex)
     {
         Debug.Assert(false, ex.ToString());
         return(false);
     }
     return(true);
 }
Beispiel #2
0
    void ClearLogsForTracker(CTracker tracker)
    {
        int now = CTime.GetTime(DateTime.UtcNow);

        try
        {
            using (CDatabase db = Configuration.inst().GetDB())
            {
                if (!db.IsConnected())
                {
                    m_Logger.Push(LogLevel.ERROR, 0, "Не удалось соединиться с БД");
                    return;
                }

                int storedatatime = now - tracker.m_nDaysToStore * 86400;

                using (MySqlCommand cmd = new MySqlCommand("DELETE FROM Points WHERE TrackerID = " + tracker.m_nID + " AND Time < " + storedatatime, db.connection))
                    cmd.ExecuteNonQuery();

                /*string types = "";
                 * int storeunusedeventstime = now - 10 * 86400;
                 * for (int i = 0; i < CEventList.UsefulEvents.Length; i++)
                 *  types += ((i > 0) ? "," : "") + (int)CEventList.UsefulEvents[i];*/
                using (MySqlCommand cmd = new MySqlCommand("DELETE FROM Events WHERE TrackerID = " + tracker.m_nID + " AND Time < " + storedatatime + " AND Status=3", db.connection))
                    cmd.ExecuteNonQuery();
            }
        }
        catch (Exception e)
        {
            m_Logger.Push(LogLevel.ERROR, 0, e.ToString());
        }
    }
Beispiel #3
0
    string GetPacket(TrackerPacket point, int isResend)
    {
        decimal Alarm = 0;

        point.GetInput("ALARM", out Alarm);
        int timestamp, packettimestamp, servertimestamp;

        packettimestamp = point.m_Time;
        DateTime dt = CTime.GetTime(Convert.ToInt64(packettimestamp));

        servertimestamp = Convert.ToInt32(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds);
        if (isResend > 0)
        {
            timestamp = servertimestamp;
        }
        else
        {
            timestamp = packettimestamp;
        }

        string str = "{\"deviceId\": \"" + m_Tracker.m_IMEI + "\", " +
                     "\"latitude\": \"" + point.m_fLat + "\", " +
                     "\"longitude\": \"" + point.m_fLng + "\", " +
                     "\"timeStamp\": \"" + timestamp + "\", " +
                     "\"speed\": \"" + CObject.Float2XML(point.m_Speed / 3.6) + "\", " +
                     "\"sos\": \"" + ((Alarm != 0) ? "True": "False") + "\", " +
                     "\"altitude\": \"" + point.m_Alt + "\", " +
                     "\"vehicleNo\": \"" + m_Tracker.m_strName + "\", " +
                     "\"isValid\": \"" + (point.IsFixed(false) ? "True" : "False") + "\", " +
                     "\"packetTimeStamp\": \"" + packettimestamp + "\"," +
                     "\"serverTimeStamp\": \"" + servertimestamp + "\"" +
                     "}";

        return(str);
    }
Beispiel #4
0
    ////////////////////////////////////////////////////////////////////////
    ////ATL861693035354588,$GPRMC,061627,A,2306.4575,N,07238.3892,E,0,0,250317,,,*3D,#01111011000001,0,0,0,0.00,46.04,4.0,10,404,98,145d,d11cATL
    public bool ProcessPacket(string str)
    {
        if (str[0] != 0x20)
        {
            return(false);
        }

        char msgType = str[1];

        string[] slices = str.Split(',');  //части сообщени¤

        if (m_IMEI == 0)
        {
            if (!long.TryParse(slices[0].Substring(5, slices[0].Length - 5), out m_IMEI) || !IMEIIsValid())
            {
                return(false);
            }
        }

        TrackerPacket packet = new TrackerPacket(m_IMEI);

        if (slices[10].Length == 6 && slices[2].Length >= 6)
        {
            packet.m_Time = CTime.GetTime(slices[10], slices[2]);
        }

        packet.m_SatteliteCount = (slices[3] == "A") ? (byte)3 : (byte)0;

        if (slices[4].Length == 9)
        {
            packet.m_fLat = (int.Parse(slices[4].Substring(0, 2)) + (float.Parse(slices[4].Substring(2, 7), m_Format) / 60)) * (slices[5] == "S" ? -1 : 1);
        }
        if (slices[6].Length == 10)
        {
            packet.m_fLng = (int.Parse(slices[6].Substring(0, 3)) + (float.Parse(slices[6].Substring(3, 7), m_Format) / 60)) * (slices[7] == "W" ? -1 : 1);
        }
        if (slices[8].Length > 0)
        {
            packet.m_Speed = (ushort)(float.Parse(slices[8], m_Format) * 1.852);
        }
        if (slices[9].Length > 0)
        {
            packet.m_Direction = (ushort)(float.Parse(slices[9], m_Format));
        }

        slices[14] = slices[14].Replace("#", "");
        packet.SetInput("DIN1", (slices[14][0] == '1') ? 1 : 0);
        packet.SetInput("DIN2", (slices[14][1] == '1') ? 1 : 0);
        packet.SetInput("ALARM", (slices[14][2] == '0') ? 1 : 0);
        packet.SetInput("ACCEL", (slices[14][8] == '1') ? 1 : 0);
        packet.SetInput("BREAK_ACCEL", (slices[14][9] == '1') ? 1 : 0);

        packet.SetInput("PWR", float.Parse(slices[15], m_Format) * 12);
        packet.SetInput("ODO", float.Parse(slices[18], m_Format));
        packet.SetInput("ACC", float.Parse(slices[20], m_Format));

        return(PushPacket(packet));
    }
Beispiel #5
0
    public override DBQuery GetInsertQuery(CUser user, CUser newUser)//TODO: newUser пока не используется
    {
        if (!user.CanDo(CUser.ACL.EDITUSERS) && !user.CanDo(CUser.ACL.EDIT_ALL_USERS))
        {
            return(null);
        }
        int time = CTime.GetTime(DateTime.Now);

        return(new DBQuery("INSERT INTO Users(Name, ParentUserID) VALUES(\"u" + time % 10000 + "." + DateTime.Now.Millisecond + "\", " + user.m_nID + ")"));
    }
Beispiel #6
0
    string GetPacket(TrackerPacket point)
    {
        decimal key = 0;

        point.GetInput("EKEY", out key);

        DateTime dt  = CTime.GetTime(point.m_Time);
        string   str = dt.ToString("ddMMyy") + ";" +
                       dt.ToString("HHmmss") + ";" +
                       GetCoord(Math.Abs(point.m_fLat), true) + ";" +
                       ((point.m_fLat > 0) ? "N" : "S") + ";" +
                       GetCoord(Math.Abs(point.m_fLng), false) + ";" +
                       ((point.m_fLng > 0) ? "E" : "W") + ";" +
                       point.m_Speed + ";" +
                       point.m_Direction + ";" +
                       point.m_Alt + ";" +
                       point.m_SatteliteCount + ";" +
                       "0" + ";" +
                       ";" +
                       ";" +
                       ";" +
                       ((key > 0) ? ((long)key).ToString("X12") : "NA") + ";";

        byte[] inputs = point.GetIOBuffer();
        if (inputs != null)
        {
            int i = 0;
            while (i < inputs.Length)
            {
                ushort id     = BitConverter.ToUInt16(inputs, i);
                bool   b64bit = (id & (1 << (int)TrackerPacket.IOFlags.LENGTH8)) != 0;
                i += 2 + (b64bit ? 8 : 4);

                decimal fValue = 0;
                string  name   = IOChannelMgr.inst().GetIOChannel((ushort)(id & 0xFFF));
                if (name != null && point.GetInput(name, out fValue))
                {
                    if ((id & (1 << (int)TrackerPacket.IOFlags.INTEGER)) != 0)
                    {
                        str += name + ":1:" + fValue + ",";
                    }
                    else
                    {
                        str += name + ":2:" + CObject.Float2XML(fValue) + ",";
                    }
                }
            }
        }
        return(str.Trim(','));
    }
Beispiel #7
0
    string GetPacket(TrackerPacket point, int isResend)
    {
        DateTime dt = CTime.GetTime(point.m_Time);
        decimal  odo = 0, pwr = 0, acc = 0, ign = 1; byte satcount = 0;

        point.GetInput("ODO", out odo); point.GetInput("PWR", out pwr); point.GetInput("DIN1", out ign);
        string IMEI, latitude, latDirection, longitude, longDirection, alt, speed, heading, date, time, valid;

        IMEI          = m_Tracker.m_IMEI.ToString();
        latitude      = toNMEA(point.m_fLat);
        latDirection  = ((point.m_fLat >= 0) ? "N" : "S");
        longitude     = toNMEA(point.m_fLng);
        longDirection = ((point.m_fLng >= 0) ? "E" : "W");
        speed         = Convert.ToString(Convert.ToDouble(point.m_Speed / 1.852));
        alt           = point.m_Alt.ToString();
        heading       = point.m_Direction.ToString();
        satcount      = point.m_SatteliteCount;
        date          = dt.ToString("ddMMyy");
        if (isResend == 0)
        {
            time = dt.ToString("HHmmss.fff");
        }
        else
        {
            time = DateTime.UtcNow.ToString("HHmmss.fff");
        }

        // valid=point.IsFixed(false)?"1":"0";
        valid = "1";
        if (res.Equals(""))
        {
            res = String.Format("$FRCMD,{0},_SendMessage,,{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},Button1={11},Button2={12},Analog1={13},BatteryLow={14},{15}",
                                IMEI, latitude, latDirection, longitude, longDirection, alt,
                                speed, heading, date, time, valid, ign, isResend, satcount, acc, "*74A");
        }
        string newchar = "";

        checksum = getChecksum(res.ToCharArray());
        newchar += ((char)(((checksum >> 4) & 0xf) > 9 ? ((checksum) & 0xf) + 'A' - 10 : ((checksum >> 4) & 0xf) + '0'));
        newchar += (char)((checksum & 0xf) > 9 ? (checksum & 0xf) + 'A' - 10 : ((checksum & 0xf)) + '0');
        res      = String.Format("$FRCMD,{0},_SendMessage,,{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},Button1={11},Button2={12},Analog1={13},BatteryLow={14},{15}",
                                 IMEI, latitude, latDirection, longitude, longDirection, alt,
                                 speed, heading, date, time, valid, ign, isResend, satcount, acc, "*" + newchar);
        m_Logger.Push(LogLevel.INFO, 0, res);
        return(res);
    }
Beispiel #8
0
    ///////////////////////////////////////////////////////////////
    public override string ToString()
    {
        DateTime dt     = CTime.GetTime(m_Time).ToLocalTime();
        string   result = "IMEI=" + m_ID +
                          " Time=" + dt.ToString("dd.MM.yyyy-HH:mm:ss") +
                          " Lat=" + Float2XML(m_fLat) +
                          " Lng=" + Float2XML(m_fLng) +
                          " Alt=" + m_Alt +
                          " Dir=" + m_Direction +
                          " Speed=" + m_Speed +
                          " GSM=" + m_ulMNID +
                          " Sat=" + m_SatteliteCount;

        if (m_Inputs != null)
        {
            int i = 0;
            while (i < m_Inputs.Length)
            {
                int  id     = (int)BitConverter.ToUInt16(m_Inputs, i);
                bool b64bit = (id & (1 << (int)IOFlags.LENGTH8)) != 0;

                decimal fValue;
                if ((id & (1 << (int)IOFlags.INTEGER)) != 0)
                {
                    if (b64bit)
                    {
                        fValue = BitConverter.ToUInt64(m_Inputs, i + 2);
                    }
                    else
                    {
                        fValue = BitConverter.ToInt32(m_Inputs, i + 2);
                    }
                }
                else
                {
                    fValue = (decimal)(b64bit ? BitConverter.ToDouble(m_Inputs, i + 2) : BitConverter.ToSingle(m_Inputs, i + 2));
                }
                result += " " + IOChannelMgr.inst().GetIOChannel((ushort)(id & 0xFFF)) + "=" + Float2XML(fValue);

                i += 2 + (b64bit ? 8 : 4);
            }
        }
        return(result);
    }
Beispiel #9
0
    // У$DIMTS,null,null,null,357852031069696,DL1PC4716,31.12.2013,06:54:11,28.5271550,null,77.2807010,null,12.5,1,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null#Ф
    string GetPacket(TrackerPacket point)
    {
        DateTime dt = CTime.GetTime(point.m_Time);
        decimal  odo = 0, pwr = 0, acc = 0;

        point.GetInput("ODO", out odo);
        point.GetInput("ACC", out acc);
        point.GetInput("PWR", out pwr);

        string res = "$DIMTS,null,null,null";

        res += "," + m_Tracker.m_IMEI;
        res += "," + m_Tracker.m_strName;
        res += "," + dt.ToString("dd.MM.yyyy");
        res += "," + dt.ToString("HH:mm:ss");
        res += "," + CObject.Float2XML(Math.Abs(point.m_fLat));
        res += "," + ((point.m_fLat >= 0) ? "N" : "S");
        res += "," + CObject.Float2XML(Math.Abs(point.m_fLng));
        res += "," + ((point.m_fLng >= 0) ? "E" : "W");
        res += "," + point.m_Speed;
        res += "," + (point.IsFixed(false) ? "1" : "0");
        res += "," + point.m_SatteliteCount;
        res += ",null";// + 1; //DOP
        res += "," + point.m_Direction;
        res += "," + point.m_Alt;
        res += ",null";               // + 0;
        res += "," + Math.Round(odo); //ODO
        res += ",null";               //IGN
        res += ",null";               // + CObject.Float2XML((double)acc / 1000.0); //Batt
        res += ",null";               // + CObject.Float2XML((double)pwr / 1000.0); //POWER
        res += ",null";               // + "00000000"; //Digitalinputvalues
        res += ",null";               //NetworkOperatorName
        res += ",null";               // + 15; //GSMStrength
        res += ",null";               // + 0; //CellID
        res += ",null";               // + 0; //LAC
        res += ",null";               // + 1; //SeqNo
        res += ",null";               // + 0; //AvgSpd
        res += ",null";               // + 0; //MinSpd
        res += "#";

        m_Logger.Push(LogLevel.INFO, 0, res);

        return(res);
    }
Beispiel #10
0
    public CTracker GetNextTracker()
    {
        int now = CTime.GetTime(DateTime.UtcNow);

        lock (m_Trackers)
            if (m_Trackers.Count > 0)
            {
                for (int i = 0; i < m_Trackers.Count; i++)
                {
                    m_nTracker = (m_nTracker + 1) % m_Trackers.Count;
                    if (!m_Times.ContainsKey(m_Trackers[m_nTracker].m_nID) || m_Times[m_Trackers[m_nTracker].m_nID] < now - 5)
                    {
                        m_Times[m_Trackers[m_nTracker].m_nID] = now;
                        return(m_Trackers[m_nTracker]);
                    }
                }
            }
        return(null);
    }
Beispiel #11
0
    ////////////////////////////////////////////////////////////////////////
    bool ParsePositionPacket(string[] slices)
    {
        TrackerPacket packet = new TrackerPacket(m_IMEI);

        packet.m_Time = CTime.GetTime(slices[3] + slices[4] + slices[5], slices[6] + slices[7] + slices[8]);

        //координаты
        packet.m_fLat = float.Parse(slices[9].Substring(0, slices[9].Length - 1), m_Format) * (slices[9][slices[9].Length - 1] == 'S' ? -1 : 1);
        packet.m_fLng = float.Parse(slices[10].Substring(0, slices[10].Length - 1), m_Format) * (slices[10][slices[10].Length - 1] == 'W' ? -1 : 1);

        packet.m_Speed     = (ushort)float.Parse(slices[11], m_Format);
        packet.m_Direction = ushort.Parse(slices[12]);
        packet.SetInput("HDOP", float.Parse(slices[13], m_Format));
        packet.m_Alt = (short)float.Parse(slices[14], m_Format);
        packet.SetInput("ODO", float.Parse(slices[15], m_Format));

        packet.SetInput("DIN1", (slices[16] == "1") ? 1 : 0);
        packet.SetInput("DIN2", (slices[17] == "1") ? 1 : 0);
        packet.SetInput("DIN3", (slices[18] == "1") ? 1 : 0);
        packet.SetInput("DIN4", (slices[19] == "1") ? 1 : 0);
        packet.SetInput("DOUT1", (slices[20] == "1") ? 1 : 0);
        packet.SetInput("DOUT2", (slices[21] == "1") ? 1 : 0);
        packet.SetInput("DOUT3", (slices[22] == "1") ? 1 : 0);
        packet.SetInput("DOUT4", (slices[23] == "1") ? 1 : 0);

        packet.SetInput("AIN1", float.Parse(slices[24], m_Format));
        packet.SetInput("AIN2", float.Parse(slices[25], m_Format));
        packet.SetInput("AIN3", float.Parse(slices[26], m_Format));
        packet.SetInput("AIN4", float.Parse(slices[27], m_Format));

        //iWare  28

        packet.SetInput("PWR", float.Parse(slices[29], m_Format));
        packet.SetInput("ACC", float.Parse(slices[30], m_Format));
        //packet.SetInput("GSM", float.Parse(slices[31], m_Format));
        packet.m_SatteliteCount = (slices[34] == "A") ? byte.Parse(slices[32]) : (byte)0;
        //packet.SetInput("RS232", long.Parse(slices[33]));

        return(PushPacket(packet));
    }
Beispiel #12
0
    //////////////////////////////////////////////////////////////////////////
    void Tick(object obj)
    {
        if (m_bRunning)
        {
            return;
        }
        m_bRunning = true;

        int now = CTime.GetTime(DateTime.UtcNow);

        if (m_LastTrackerListLoadTime < now - 12 * 3600 && m_nTrackerIndex >= m_Trackers.Count)
        {
            m_Trackers = ConfigMgr.inst().GetTrackers();
            m_LastTrackerListLoadTime = now;
            m_nTrackerIndex           = 0;

            ClearCommonLogs();
            int t = CTime.GetTime(DateTime.UtcNow);
            if (t - now > 1)
            {
                m_Logger.Push(LogLevel.WARNING, 0, "Common data cleared for " + (t - now) + " sec");
            }
        }

        now = CTime.GetTime(DateTime.UtcNow);
        if (m_nTrackerIndex < m_Trackers.Count)
        {
            CTracker tracker = m_Trackers[m_nTrackerIndex++];
            ClearLogsForTracker(tracker);

            int t = CTime.GetTime(DateTime.UtcNow);
            if (t - now > 1)
            {
                m_Logger.Push(LogLevel.WARNING, 0, "Data for " + tracker.GetDesc() + " cleared for " + (t - now) + " sec");
            }
        }

        m_bRunning = false;
    }
Beispiel #13
0
    void ClearCommonLogs()
    {
        try
        {
            using (CDatabase db = Configuration.inst().GetDB())
            {
                if (!db.IsConnected())
                {
                    m_Logger.Push(LogLevel.ERROR, 0, "Не удалось соединиться с БД");
                    return;
                }

                int time = CTime.GetTime(DateTime.UtcNow) - 86400;
                using (MySqlCommand cmd = new MySqlCommand("UPDATE events SET status = status | 1 where status = 2 AND Time < " + time, db.connection))
                    cmd.ExecuteNonQuery();
            }
        }
        catch (Exception e)
        {
            m_Logger.Push(LogLevel.ERROR, 0, e.ToString());
        }
    }
Beispiel #14
0
        string GetPacket(TrackerPacket point)
        {
            DateTime dt = CTime.GetTime(point.m_Time);
            decimal  odo = 0, pwr = 0, acc = 0, ign = 0;

            point.GetInput("ODO", out odo);
            point.GetInput("ACC", out acc);
            point.GetInput("PWR", out pwr);
            point.GetInput("DIN1", out ign);
            string IMEI, latitude, latDirection, longitude, longDirection, alt, speed, heading, date, time, valid;

            IMEI          = m_Tracker.m_IMEI.ToString();
            latitude      = toNMEA(point.m_fLat);
            latDirection  = ((point.m_fLat >= 0) ? "N" : "S");
            longitude     = toNMEA(point.m_fLng);
            longDirection = ((point.m_fLng >= 0) ? "E" : "W");
            speed         = Convert.ToString(Convert.ToDouble(point.m_Speed / 1.852));
            alt           = point.m_Alt.ToString();
            heading       = point.m_Direction.ToString();
            date          = dt.ToString("ddMMyy");
            time          = dt.ToString("HHmmss.fff");
            // valid=point.IsFixed(false)?"1":"0";
            valid = "1";
            if (res.Equals(""))
            {
                res = String.Format("${0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12}#",
                                    IMEI, date, time, latitude, latDirection, longitude, longDirection, alt,
                                    speed, heading, valid, ign, "*74A");
            }
            string newchar = "";

            checksum = getChecksum(res.ToCharArray());
            newchar += ((char)(((checksum >> 4) & 0xf) > 9 ? ((checksum) & 0xf) + 'A' - 10 : ((checksum >> 4) & 0xf) + '0'));
            newchar += (char)((checksum & 0xf) > 9 ? (checksum & 0xf) + 'A' - 10 : ((checksum & 0xf)) + '0');
            res      = String.Format("${0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12}#",
                                     IMEI, date, time, latitude, latDirection, longitude, longDirection, alt, speed, heading, valid, ign, "*" + newchar);
            m_Logger.Push(LogLevel.INFO, 0, res);
            return(res);
        }
Beispiel #15
0
    void PutExtData2Packet(TrackerPacket packet)
    {
        if (Math.Abs(CTime.GetTime(DateTime.UtcNow) - packet.m_Time) < 600)
        {
            if (m_fAcc >= 0)
            {
                packet.SetInput("ACC", m_fAcc);

                packet.SetInput("DIN1", ((m_LastStatusByte & 2) != 0) ? 1 : 0);//Ignition
                packet.SetInput("DIN2", ((m_LastStatusByte & 128) != 0) ? 1 : 0);
            }
            if (m_fPwr >= 0)
            {
                packet.SetInput("PWR", m_fPwr);
            }
            if (m_fDoor >= 0)
            {
                packet.SetInput("IN1", m_fDoor);
            }
            packet.SetInput("STATUS", m_iStatus);
        }
        packet.SetInput("ALARM", m_iAlarm);
    }
Beispiel #16
0
    ////////////////////////////////////////////////////////////////////////
    bool ProcessRecord(byte[] buffer, ref int from)
    {
        if (buffer[from++] != 0x78 || buffer[from++] != 0x78)
        {
            return(false);
        }

        int len = buffer[from++];

        if (from + len + 2 > buffer.Length)
        {
            return(false);
        }

        if (buffer[from + len] != 13 || buffer[from + len + 1] != 10)
        {
            return(false);
        }

        int crc = GetCrc16(buffer, from - 1, len - 1);

        if (crc != BIConverter.ToUInt16(buffer, from + len - 2))
        {
            return(false);
        }

        byte pn = buffer[from++];
        int  sn = BitConverter.ToUInt16(buffer, from + len - 5);

        switch (pn)
        {
        case 1:    //login
        {
            m_IMEI = GetNumberFromHex(buffer, from, 8);
            if (!IMEIIsValid())
            {
                return(false);
            }

            byte[] reply = new byte[10] {
                0x78, 0x78, 0x05, pn, (byte)(sn >> 8), (byte)sn, 0x00, 0x00, 0x0D, 0x0A
            };
            crc = GetCrc16(reply, 2, reply.Length - 6);
            reply[reply.Length - 4] = (byte)(crc >> 8);
            reply[reply.Length - 3] = (byte)crc;
            Send(reply, reply.Length);

            break;
        }

        case 0x10:    //GPS
        {
            TrackerPacket packet = new TrackerPacket(m_IMEI);
            if (buffer[from] > 0)
            {
                packet.m_Time = CTime.GetTime(new DateTime(2000 + buffer[from], buffer[from + 1], buffer[from + 2], buffer[from + 3], buffer[from + 4], buffer[from + 5]));
            }
            packet.m_SatteliteCount = (byte)(((buffer[from + 16] & 16) == 0) ? 0 : buffer[from + 6] & 0x0F);
            packet.m_fLat           = (float)(BIConverter.ToUInt32(buffer, from + 7) / 1800000.0 * (((buffer[from + 16] & 4) == 0) ? -1 : 1));
            packet.m_fLng           = (float)(BIConverter.ToUInt32(buffer, from + 11) / 1800000.0 * (((buffer[from + 16] & 8) == 0) ? 1 : -1));
            packet.m_Speed          = buffer[from + 15];
            packet.m_Direction      = (ushort)(BIConverter.ToUInt16(buffer, from + 16) & 0x3FF);
            if (Math.Abs(CTime.GetTime(DateTime.UtcNow) - packet.m_Time) < 600)
            {
                packet.SetInput("ACC", m_Volt);
            }
            if (!PushPacket(packet))
            {
                return(false);
            }
            break;
        }

        case 0x12:    //GPS
        {
            TrackerPacket packet = new TrackerPacket(m_IMEI);
            if (buffer[from] > 0)
            {
                packet.m_Time = CTime.GetTime(new DateTime(2000 + buffer[from], buffer[from + 1], buffer[from + 2], buffer[from + 3], buffer[from + 4], buffer[from + 5]));
            }
            packet.m_SatteliteCount = (byte)(((buffer[from + 16] & 16) == 0) ? 0 : buffer[from + 6] & 0x0F);
            packet.m_fLat           = (float)(BIConverter.ToUInt32(buffer, from + 7) / 1800000.0 * (((buffer[from + 16] & 4) == 0) ? -1 : 1));
            packet.m_fLng           = (float)(BIConverter.ToUInt32(buffer, from + 11) / 1800000.0 * (((buffer[from + 16] & 8) == 0) ? 1 : -1));
            packet.m_Speed          = buffer[from + 15];
            packet.m_Direction      = (ushort)(BIConverter.ToUInt16(buffer, from + 16) & 0x3FF);
            if (Math.Abs(CTime.GetTime(DateTime.UtcNow) - packet.m_Time) < 600)
            {
                packet.SetInput("ACC", m_Volt);
            }
            if (!PushPacket(packet))
            {
                return(false);
            }
            break;
        }

        case 0x13:    //Status package
        {
            switch (buffer[from + 1])
            {
            case 1: m_Volt = 5; break;

            case 2: m_Volt = 10; break;

            case 3: m_Volt = 30; break;

            case 4: m_Volt = 50; break;

            case 5: m_Volt = 75; break;

            case 6: m_Volt = 100; break;

            default: m_Volt = 0; break;
            }

            byte[] reply = new byte[10] {
                0x78, 0x78, 0x05, pn, (byte)(sn >> 8), (byte)sn, 0x00, 0x00, 0x0D, 0x0A
            };
            crc = GetCrc16(reply, 2, reply.Length - 6);
            reply[reply.Length - 4] = (byte)(crc >> 8);
            reply[reply.Length - 3] = (byte)crc;
            Send(reply, reply.Length);
            break;
        }

        case 0x16:    //GPS LBS status combined package
        {
            byte[] reply = new byte[15] {
                0x78, 0x78, 11, pn, 0, 0x00, 0x00, 0x00, 0x01, (byte)(sn >> 8), (byte)sn, 0, 0, 0x0D, 0x0A
            };
            crc = GetCrc16(reply, 2, reply.Length - 6);
            reply[reply.Length - 4] = (byte)(crc >> 8);
            reply[reply.Length - 3] = (byte)crc;
            Send(reply, reply.Length);

            m_Logger.Push(LogLevel.DEBUG, 0, "GPS LBS status combined package");
            break;
        }

        case 0x17:    //LBS telephone number address searching package
        {
            byte[] reply = new byte[15] {
                0x78, 0x78, 11, pn, 0, 0x00, 0x00, 0x00, 0x01, (byte)(sn >> 8), (byte)sn, 0, 0, 0x0D, 0x0A
            };
            crc = GetCrc16(reply, 2, reply.Length - 6);
            reply[reply.Length - 4] = (byte)(crc >> 8);
            reply[reply.Length - 3] = (byte)crc;
            Send(reply, reply.Length);
            m_Logger.Push(LogLevel.DEBUG, 0, "LBS telephone number address searching package");
            break;
        }

        case 0x18:    //LBS extension package
        {
            TrackerPacket packet = new TrackerPacket(m_IMEI);
            if (buffer[from] > 0)
            {
                packet.m_Time = CTime.GetTime(new DateTime(2000 + buffer[from], buffer[from + 1], buffer[from + 2], buffer[from + 3], buffer[from + 4], buffer[from + 5]));
            }
            packet.SetGSMInfo(BIConverter.ToUInt16(buffer, from + 6), buffer[from + 8], BIConverter.ToUInt16(buffer, from + 9), BIConverter.ToUInt16(buffer, from + 12));
            if (Math.Abs(CTime.GetTime(DateTime.UtcNow) - packet.m_Time) < 600)
            {
                packet.SetInput("ACC", m_Volt);
            }
            if (!PushPacket(packet))
            {
                return(false);
            }
            break;
        }

        case 0x19:    //LBS status combined package
        {
            byte[] reply = new byte[15] {
                0x78, 0x78, 11, pn, 0, 0x00, 0x00, 0x00, 0x01, (byte)(sn >> 8), (byte)sn, 0, 0, 0x0D, 0x0A
            };
            crc = GetCrc16(reply, 2, reply.Length - 6);
            reply[reply.Length - 4] = (byte)(crc >> 8);
            reply[reply.Length - 3] = (byte)crc;
            Send(reply, reply.Length);
            m_Logger.Push(LogLevel.DEBUG, 0, "LBS status combined package");
            break;
        }

        case 0x1A:    //GPS telephone number address searching package
        {
            byte[] reply = new byte[15] {
                0x78, 0x78, 11, pn, 0, 0x00, 0x00, 0x00, 0x01, (byte)(sn >> 8), (byte)sn, 0, 0, 0x0D, 0x0A
            };
            crc = GetCrc16(reply, 2, reply.Length - 6);
            reply[reply.Length - 4] = (byte)(crc >> 8);
            reply[reply.Length - 3] = (byte)crc;
            Send(reply, reply.Length);
            m_Logger.Push(LogLevel.DEBUG, 0, "GPS telephone number address searching package");
            break;
        }

        case 0x1F:    //Time Synchronization packets
        {
            long   time  = CTime.GetTime(DateTime.UtcNow);
            byte[] reply = new byte[14] {
                0x78, 0x78, 10, pn, (byte)(time >> 24), (byte)(time >> 16), (byte)(time >> 8), (byte)(time), (byte)(sn >> 8), (byte)sn, 0, 0, 0x0D, 0x0A
            };
            crc = GetCrc16(reply, 2, reply.Length - 6);
            reply[reply.Length - 4] = (byte)(crc >> 8);
            reply[reply.Length - 3] = (byte)crc;
            Send(reply, reply.Length);
            m_Logger.Push(LogLevel.DEBUG, 0, "Time Synchronization package ");
            break;
        }

        case 0x80:    //Command Package
        case 0x81:    //
        {
            /*byte[] reply = new byte[] { 0x78, 0x78, 0x1A, pn, 0x12, 0x00, 0x46, 0x04, 0x46, 0x50, 0x41, 0x52, 0x41, 0x4D, 0x3D, 0x53, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x21, 0x00, 0x02, 0x00, 0x6D, 0x72, 0x7D, 0x0D, 0x0A };
             * crc = GetCrc16(reply, 2, reply.Length - 6);
             * reply[reply.Length - 4] = (byte)(crc >> 8);
             * reply[reply.Length - 3] = (byte)crc;
             * Send(reply, reply.Length);*/
            break;
        }

        default:
        {
            m_Logger.Push(LogLevel.DEBUG, 0, "unknown package " + pn);
            break;
        }
        }
        from += len - 1; //13 10
        from += 2;       //13 10
        return(true);
    }
Beispiel #17
0
    byte[] GetPacket(TrackerPacket point)
    {
        int i = 0;

        byte[] buf = new byte[45 + 20];
        for (int j = 0; j < buf.Length; j++)
        {
            buf[j] = 0;
        }

        buf[i++] = 0x29;
        buf[i++] = 0x29;
        buf[i++] = 0x80;
        i       += 2; // length

        uint imei = (uint)(m_Tracker.m_IMEI - 14100000000);

        for (int k = 0; k < 4; k++)
        {
            buf[i + 3 - k] = (byte)(imei % 100);
            if (k != 2)
            {
                buf[i + 3 - k] |= 0x80;
            }
            imei = imei / 100;
        }
        i += 4;

        DateTime dt = CTime.GetTime(point.m_Time + 3600 * 2);

        buf[i++] = BCDConverter.GetBytes(dt.Year - 2000, 1)[0];
        buf[i++] = BCDConverter.GetBytes(dt.Month, 1)[0];
        buf[i++] = BCDConverter.GetBytes(dt.Day, 1)[0];
        buf[i++] = BCDConverter.GetBytes(dt.Hour, 1)[0];
        buf[i++] = BCDConverter.GetBytes(dt.Minute, 1)[0];
        buf[i++] = BCDConverter.GetBytes(dt.Second, 1)[0];

        GetCoord(point.m_fLat).CopyTo(buf, i); i += 4;
        GetCoord(point.m_fLng).CopyTo(buf, i); i += 4;

        BCDConverter.GetBytes(point.m_Speed, 2).CopyTo(buf, i); i     += 2;
        BCDConverter.GetBytes(point.m_Direction, 2).CopyTo(buf, i); i += 2;

        decimal odo = 0, ignition = 0, oilcut = 0, pwr = 12000;
        decimal din1 = 0, din2 = 0, din3 = 0, din4 = 0;

        point.GetInput("DIN6", out ignition);
        point.GetInput("DIN7", out oilcut);
        point.GetInput("PWR", out pwr);
        point.GetInput("ODO", out odo);
        point.GetInput("DIN1", out din1);
        point.GetInput("DIN2", out din2);
        point.GetInput("DIN3", out din3);
        point.GetInput("DIN4", out din4);

        BIConverter.GetBytes((int)odo).CopyTo(buf, i);
        buf[i++] = (byte)(((pwr == 0) ? 16 : (pwr > 3000) ? 24 : 8) + ((point.IsFixed(false) ? 224 : 0)));
        i       += 3;

        buf[i++] = (byte)(1 +
                          ((oilcut > 0) ? 0 : 4) +
                          ((din1 > 0) ? 0 : 8) +
                          ((din2 > 0) ? 0 : 16) +
                          ((din3 > 0) ? 0 : 32) +
                          ((din4 > 0) ? 0 : 64) +
                          ((ignition > 0) ? 0 : 128)); //ign, pwr, oil cut
        buf[i++] = 0xFC;                               //alarms
        buf[i++] = 0x36;                               // 32;//tcp
        buf[i++] = 0x00;

        buf[i++] = 0x00;
        buf[i++] = 0x78;
        buf[i++] = 0x00;
        buf[i++] = 0x00;
        buf[i++] = 0x00;
        buf[i++] = 0x00;
        buf[i++] = 0x3C;
        buf[i++] = 0x00;

        decimal fuel = 0;

        if (point.GetInput("FUEL", out fuel))
        {
            string data = fuel.ToString("000.00").Replace(",", ".");
            BIConverter.GetBytes((ushort)(data.Length + 2)).CopyTo(buf, i); i += 2;
            BIConverter.GetBytes((ushort)0x0023).CopyTo(buf, i); i            += 2;
            Encoding.ASCII.GetBytes(data).CopyTo(buf, i);
            i += data.Length;
        }
        if (point.GetInput("AIN5", out fuel))
        {
            BIConverter.GetBytes((ushort)4).CopyTo(buf, i); i      += 2;
            BIConverter.GetBytes((ushort)0x002D).CopyTo(buf, i); i += 2;
            BIConverter.GetBytes((ushort)fuel).CopyTo(buf, i); i   += 2;
        }

        BIConverter.GetBytes((ushort)(i - 3)).CopyTo(buf, 3);
        buf[i++] = GetCRC(buf, 0, i);
        buf[i++] = 0x0D;

        byte[] res = new byte[i];

        string str = "<<";

        for (int j = 0; j < i; j++)
        {
            res[j] = buf[j];
            str   += " " + buf[j].ToString("X2");
        }
        m_Logger.Push(LogLevel.INFO, 0, str);

        return(res);
    }
Beispiel #18
0
    protected void Tick(object obj)
    {
        int cnt = 0;

        if (m_bRunning)
        {
            return;
        }

        m_bRunning = true;
        try
        {
            m_Tracker = m_config.GetNextTracker();
            if (m_Tracker == null)
            {
                m_bRunning = false;
                return;
            }
            TrackerPacketList pts;
            DateTime          start = DateTime.UtcNow;
            using (CDatabase db = Configuration.inst().GetDB()) {
                pts = GetPoint(db);
                if (pts != null && pts.Count > 0)
                {
                    DateTime dt = CTime.GetTime(Convert.ToInt64(pts[0].m_Time));
                    if (dt <= DateTime.UtcNow)
                    {
                        if (((System.DateTime.UtcNow.AddMinutes(-3)) > dt && pts[0].m_Speed == 0) && m_config.StaticDataResend)
                        {
                            cnt = DoSession(pts, 1);
                        }
                        else
                        {
                            if (dt > (System.DateTime.UtcNow.AddMinutes(-3)))
                            {
                                cnt = DoSession(pts, 0);
                            }
                        }
                    }
                    else
                    {
                        EmailSender.inst().AddMessage(m_config.EmailAddr, pts[0].m_ID + " Is Sending Future Time Stamp Data");
                    }
                    if (System.DateTime.Now > System.DateTime.UtcNow.AddHours(5).AddMinutes(30))
                    {
                        EmailSender.inst().AddMessage(m_config.EmailAddr, System.Net.Dns.GetHostName() + " Has Wrong Date Time Setting");
                    }
                    DateTime delete = DateTime.UtcNow;
                    if (cnt == pts.Count && DeletePoint(db, pts))
                    {
                        m_Logger.Push(LogLevel.INFO, 0, cnt + " point sent of " + pts.Count +
                                      ".Times for query/session/delete:" + (DateTime.UtcNow - start).TotalMilliseconds + "/" + (delete - DateTime.UtcNow).TotalMilliseconds + "/" + (DateTime.UtcNow - delete).TotalMilliseconds);
                        m_LastFailTime = 0;
                    }
                    if (cnt == 0 && m_LastFailTime == 0)
                    {
                        m_LastFailTime = CTime.GetTime(DateTime.UtcNow);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            m_Logger.Push(LogLevel.ERROR, 0, m_Tracker.m_IMEI + " Error sending points " + ex.ToString());
            if (m_LastFailTime == 0)
            {
                m_LastFailTime = CTime.GetTime(DateTime.UtcNow);
            }
        }
        try
        {
            if (m_LastFailTime > 0 && CTime.GetTime(DateTime.UtcNow) > m_LastFailTime + m_config.MaxFailTimeBeforeEmail)
            {
                m_LastFailTime = -1;
                EmailSender.inst().AddMessage(m_config.EmailAddr, m_config.EmailContent);
            }
        }
        catch (Exception ex)
        {
            m_Logger.Push(LogLevel.ERROR, 0, m_Tracker.m_IMEI + " Error in connection " + ex.ToString());
        }
        m_bRunning = false;
    }
Beispiel #19
0
 public bool IsValid()
 {
     return((m_ID > 0) && (m_Time > 1262304000 /*2010*/) && (m_Time < CTime.GetTime(DateTime.Now) + 3600 * 24));
 }
Beispiel #20
0
    public bool TryParse(string s)
    {
        if (s.IndexOf("IMEI") < 0)
        {
            return(false);
        }
        s = s.Substring(s.IndexOf("IMEI"));
        s = s.Replace(" = ", "=");
        s = s.Replace(",", ".");

        string[] arr = s.Split(' ');
        if (arr.Length < 7)
        {
            return(false);
        }

        NumberFormatInfo format = new NumberFormatInfo();

        format.NumberDecimalSeparator = ".";

        for (int i = 0; i < arr.Length; i++)
        {
            if (arr[i].IndexOf("=") >= 0)
            {
                string[] pair = arr[i].Split('=');
                switch (pair[0])
                {
                case "IMEI":
                    if (!long.TryParse(pair[1], out m_ID))
                    {
                        return(false);
                    }
                    break;

                case "Time":
                    string[] digs = pair[1].Split(new char[] { '.', ':', '-' });
                    DateTime dt   = new DateTime(int.Parse(digs[2]), int.Parse(digs[1]), int.Parse(digs[0]), int.Parse(digs[3]), int.Parse(digs[4]), int.Parse(digs[5]), DateTimeKind.Local);
                    m_Time = CTime.GetTime(dt.ToUniversalTime());
                    break;

                case "Lat":
                    if (!float.TryParse(pair[1], NumberStyles.Float, format, out m_fLat))
                    {
                        return(false);
                    }
                    break;

                case "Lng":
                    if (!float.TryParse(pair[1], NumberStyles.Float, format, out m_fLng))
                    {
                        return(false);
                    }
                    break;

                case "Alt":
                    if (!short.TryParse(pair[1], out m_Alt))
                    {
                        return(false);
                    }
                    break;

                case "Speed":
                    if (!ushort.TryParse(pair[1], out m_Speed))
                    {
                        return(false);
                    }
                    break;

                case "Dir":
                    ushort dir = 0;
                    if (!ushort.TryParse(pair[1], out dir))
                    {
                        return(false);
                    }
                    m_Direction = dir;
                    break;

                case "Sat":
                    byte sat = 0;
                    if (!byte.TryParse(pair[1], out sat))
                    {
                        return(false);
                    }
                    m_SatteliteCount = sat;
                    break;

                case "GSM":
                    ulong GSMInfo = 0;
                    if (!ulong.TryParse(pair[1], out GSMInfo))
                    {
                        return(false);
                    }
                    m_ulMNID = GSMInfo;
                    break;

                default:
                    float f = 0;
                    if (!float.TryParse(pair[1], NumberStyles.Float, format, out f))
                    {
                        return(false);
                    }
                    SetInput(pair[0], f);
                    break;
                }
            }
        }
        return(IsValid());
    }
Beispiel #21
0
 public override DBQuery GetInsertQuery(CUser user, CTracker tracker)
 {
     return((user.CanDo(CUser.ACL.EDIT) && user.CanDo(CUser.ACL.EDIT_TRACKERS_IMEI)) ? new DBQuery("INSERT INTO Trackers (UserID, CreateDate) VALUES ('" + user.m_nID + "', " + CTime.GetTime(DateTime.UtcNow) + ")") : null);
 }
Beispiel #22
0
    ////////////////////////////////////////////////////////////////////////
    bool ProcessRecord(byte[] buffer, ref int from)
    {
        bool len2bytes = buffer[from] == 0x79;

        if ((buffer[from] != 0x78 && buffer[from] != 0x79) || buffer[from + 1] != buffer[from])
        {
            return(false);
        }
        from += 2;

        int len = len2bytes ? (BIConverter.ToUInt16(buffer, from)) : buffer[from];

        from += len2bytes ? 2 : 1;

        if (from + len + 2 > buffer.Length)
        {
            return(false);
        }

        if (buffer[from + len] != 13 || buffer[from + len + 1] != 10)
        {
            return(false);
        }

        int crc = GetCrc16(buffer, from - (len2bytes ? 2 : 1), len - 2 + (len2bytes ? 2 : 1));

        if (crc != BIConverter.ToUInt16(buffer, from + len - 2))
        {
            return(false);
        }

        byte pn = buffer[from++];
        int  sn = BIConverter.ToUInt16(buffer, from + len - 5);

        switch (pn)
        {
        case 1:    //login
        {
            m_IMEI = GetNumberFromHex(buffer, from, 8);
            if (!IMEIIsValid())
            {
                return(false);
            }

            byte[] reply = new byte[10] {
                0x78, 0x78, 0x05, pn, (byte)(sn >> 8), (byte)sn, 0x00, 0x00, 0x0D, 0x0A
            };
            crc = GetCrc16(reply, 2, reply.Length - 6);
            reply[reply.Length - 4] = (byte)(crc >> 8);
            reply[reply.Length - 3] = (byte)crc;
            Send(reply, reply.Length);
            break;
        }

        case 0x10:    //GPS
        {
            TrackerPacket packet = new TrackerPacket(m_IMEI);
            if (buffer[from] > 0)
            {
                packet.m_Time = CTime.GetTime(new DateTime(2000 + buffer[from], buffer[from + 1], buffer[from + 2], buffer[from + 3], buffer[from + 4], buffer[from + 5]));
            }
            packet.m_SatteliteCount = (byte)(((buffer[from + 16] & 16) == 0) ? 0 : buffer[from + 6] & 0x0F);
            packet.m_fLat           = (float)(BIConverter.ToUInt32(buffer, from + 7) / 1800000.0 * (((buffer[from + 16] & 4) == 0) ? -1 : 1));
            packet.m_fLng           = (float)(BIConverter.ToUInt32(buffer, from + 11) / 1800000.0 * (((buffer[from + 16] & 8) == 0) ? 1 : -1));
            packet.m_Speed          = buffer[from + 15];
            ushort dir = BIConverter.ToUInt16(buffer, from + 16);
            packet.m_Direction = (ushort)(dir & 0x3FF);

            PutExtData2Packet(packet);

            if (!PushPacket(packet))
            {
                return(false);
            }
            break;
        }

        case 0x12:    //location data packet
        {
            TrackerPacket packet = new TrackerPacket(m_IMEI);
            if (buffer[from] > 0)
            {
                packet.m_Time = CTime.GetTime(new DateTime(2000 + buffer[from], buffer[from + 1], buffer[from + 2], buffer[from + 3], buffer[from + 4], buffer[from + 5]));
            }
            packet.m_SatteliteCount = (byte)(((buffer[from + 16] & 16) == 0) ? 0 : buffer[from + 6] & 0x0F);
            packet.m_fLat           = (float)(BIConverter.ToUInt32(buffer, from + 7) / 1800000.0 * (((buffer[from + 16] & 4) == 0) ? -1 : 1));
            packet.m_fLng           = (float)(BIConverter.ToUInt32(buffer, from + 11) / 1800000.0 * (((buffer[from + 16] & 8) == 0) ? 1 : -1));
            packet.m_Speed          = buffer[from + 15];
            ushort dir = BIConverter.ToUInt16(buffer, from + 16);
            packet.m_Direction = (ushort)(dir & 0x3FF);

            PutExtData2Packet(packet);

            if (!PushPacket(packet))
            {
                return(false);
            }
            break;
        }

        case 0x13:    //Status package
        {
            m_LastStatusByte = buffer[from];
            switch (buffer[from + 1])
            {
            case 1: m_fAcc = 5; break;

            case 2: m_fAcc = 10; break;

            case 3: m_fAcc = 30; break;

            case 4: m_fAcc = 50; break;

            case 5: m_fAcc = 75; break;

            case 6: m_fAcc = 100; break;

            default: m_fAcc = 0; break;
            }

            byte[] reply = new byte[10] {
                0x78, 0x78, 0x05, pn, (byte)(sn >> 8), (byte)sn, 0x00, 0x00, 0x0D, 0x0A
            };
            crc = GetCrc16(reply, 2, reply.Length - 6);
            reply[reply.Length - 4] = (byte)(crc >> 8);
            reply[reply.Length - 3] = (byte)crc;
            Send(reply, reply.Length);
            break;
        }

        case 0x15:    //command reply
        {
            string str = Encoding.ASCII.GetString(buffer, from + 5, buffer[from] - 4);
            break;
        }

        case 0x16:    //GPS LBS status combined package
        {
            byte[] reply = new byte[15] {
                0x78, 0x78, 11, pn, 0, 0x00, 0x00, 0x00, 0x01, (byte)(sn >> 8), (byte)sn, 0, 0, 0x0D, 0x0A
            };
            crc = GetCrc16(reply, 2, reply.Length - 6);
            reply[reply.Length - 4] = (byte)(crc >> 8);
            reply[reply.Length - 3] = (byte)crc;
            Send(reply, reply.Length);

            TrackerPacket packet = new TrackerPacket(m_IMEI);
            if (buffer[from] > 0)
            {
                packet.m_Time = CTime.GetTime(new DateTime(2000 + buffer[from], buffer[from + 1], buffer[from + 2], buffer[from + 3], buffer[from + 4], buffer[from + 5]));
            }
            packet.m_SatteliteCount = (byte)(((buffer[from + 16] & 16) == 0) ? 0 : buffer[from + 6] & 0x0F);
            packet.m_fLat           = (float)(BIConverter.ToUInt32(buffer, from + 7) / 1800000.0 * (((buffer[from + 16] & 4) == 0) ? -1 : 1));
            packet.m_fLng           = (float)(BIConverter.ToUInt32(buffer, from + 11) / 1800000.0 * (((buffer[from + 16] & 8) == 0) ? 1 : -1));
            packet.m_Speed          = buffer[from + 15];
            ushort dir = BIConverter.ToUInt16(buffer, from + 16);
            packet.m_Direction = (ushort)(dir & 0x3FF);

            byte alarm = buffer[from + 30];
            if (alarm == 1)    //SOS
            {
                m_iAlarm = 1;
            }
            PutExtData2Packet(packet);
            m_iAlarm = 0;

            if (!PushPacket(packet))
            {
                return(false);
            }
            break;
        }

        case 0x17:    //LBS telephone number address searching package
        {
            byte[] reply = new byte[15] {
                0x78, 0x78, 11, pn, 0, 0x00, 0x00, 0x00, 0x01, (byte)(sn >> 8), (byte)sn, 0, 0, 0x0D, 0x0A
            };
            crc = GetCrc16(reply, 2, reply.Length - 6);
            reply[reply.Length - 4] = (byte)(crc >> 8);
            reply[reply.Length - 3] = (byte)crc;
            Send(reply, reply.Length);
            m_Logger.Push(LogLevel.DEBUG, 0, "LBS telephone number address searching package");
            break;
        }

        case 0x18:    //LBS extension package
        {
            break;
        }

        case 0x19:    //LBS status combined package
        {
            //StoreEvent(CEvent.EventType.ALARM, CTime.GetTime(DateTime.UtcNow), "");

            byte[] reply = new byte[15] {
                0x78, 0x78, 11, pn, 0, 0x00, 0x00, 0x00, 0x01, (byte)(sn >> 8), (byte)sn, 0, 0, 0x0D, 0x0A
            };
            crc = GetCrc16(reply, 2, reply.Length - 6);
            reply[reply.Length - 4] = (byte)(crc >> 8);
            reply[reply.Length - 3] = (byte)crc;
            Send(reply, reply.Length);
            m_Logger.Push(LogLevel.DEBUG, 0, "LBS status combined package");
            break;
        }

        case 0x1A:    //GPS telephone number address searching package
        {
            byte[] reply = new byte[15] {
                0x78, 0x78, 11, pn, 0, 0x00, 0x00, 0x00, 0x01, (byte)(sn >> 8), (byte)sn, 0, 0, 0x0D, 0x0A
            };
            crc = GetCrc16(reply, 2, reply.Length - 6);
            reply[reply.Length - 4] = (byte)(crc >> 8);
            reply[reply.Length - 3] = (byte)crc;
            Send(reply, reply.Length);
            m_Logger.Push(LogLevel.DEBUG, 0, "GPS telephone number address searching package");
            break;
        }

        case 0x1F:    //Time Synchronization packets
        {
            long   time  = CTime.GetTime(DateTime.UtcNow);
            byte[] reply = new byte[14] {
                0x78, 0x78, 10, pn, (byte)(time >> 24), (byte)(time >> 16), (byte)(time >> 8), (byte)(time), (byte)(sn >> 8), (byte)sn, 0, 0, 0x0D, 0x0A
            };
            crc = GetCrc16(reply, 2, reply.Length - 6);
            reply[reply.Length - 4] = (byte)(crc >> 8);
            reply[reply.Length - 3] = (byte)crc;
            Send(reply, reply.Length);
            m_Logger.Push(LogLevel.DEBUG, 0, "Time Synchronization package ");
            break;
        }

        case 0x80:    //Command Package
        case 0x81:    //
        {
            //need reply
            break;
        }

        case 0x8a:    //?????
        {
            break;
        }

        case 0x94:    //?????
        {
            byte id = buffer[from];
            int  k  = from + 1;
            switch (id)
            {
            case 0x00:        //power
            {
                m_fPwr = (float)(BIConverter.ToUInt16(buffer, k) / 100.0);
                k     += 2;
                break;
            }

            case 0x04:        //ascii content ALM1=75;ALM2=D5;ALM3=5F;STA1=40;DYD=01;SOS=+917226938881,+919904038880,+917226038882;CENTER=;FENCE=Fence,OFF,0,0.000000,0.000000,300,IN or OUT,1;
            {
                string str = Encoding.ASCII.GetString(buffer, k, len - 6);
                LogEvent(LogLevel.DEBUG, "0x94:     " + str);

                string[] parts = str.Split(new char[] { ';' });
                for (int i = 0; i < parts.Length; i++)
                {
                    string[] s = parts[i].Split(new char[] { '=' });
                    if (s.Length == 2)
                    {
                        switch (s[0])
                        {
                        /*case "ALM1":
                         *  m_iAlarm = m_iAlarm & 0xFFFF00;
                         *  m_iAlarm = m_iAlarm | int.Parse(s[1], System.Globalization.NumberStyles.HexNumber, null);
                         *  break;
                         * case "ALM2":
                         *  m_iAlarm = m_iAlarm & 0xFF00FF;
                         *  m_iAlarm = m_iAlarm | (int.Parse(s[1], System.Globalization.NumberStyles.HexNumber, null) << 8);
                         *  break;
                         * case "ALM3":
                         *  m_iAlarm = m_iAlarm & 0x00FFFF;
                         *  m_iAlarm = m_iAlarm | (int.Parse(s[1], System.Globalization.NumberStyles.HexNumber, null) << 16);
                         *  break;*/
                        case "STA1":
                            m_iStatus = m_iStatus & 0xFFFF00;
                            m_iStatus = m_iStatus | int.Parse(s[1], System.Globalization.NumberStyles.HexNumber, null);
                            break;

                        case "DYD":
                            m_iStatus = m_iStatus & 0xFF00FF;
                            m_iStatus = m_iStatus | (int.Parse(s[1], System.Globalization.NumberStyles.HexNumber, null) << 8);
                            break;
                        }
                    }
                }


                k += len - 6;
                break;
            }

            case 0x05:        //door status
            {
                m_fDoor = (float)buffer[k];
                k      += 1;
                break;
            }

            default:
                break;
            }
            break;
        }

        default:
        {
            m_Logger.Push(LogLevel.DEBUG, 0, "unknown package " + pn);
            break;
        }
        }
        from += len - 1; //13 10
        from += 2;       //13 10
        return(true);
    }
Beispiel #23
0
    //////////////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////
    void FlushData(object obj)    //записываем данные в базу данных
    {
        if (m_bFlushing)
        {
            return;
        }
        m_bFlushing = true;

        //записать в базу все точки
        lock (m_Queue)
            if (m_Queue.Count > 100000)
            {
                m_Queue.Clear();
                m_Logger.Push(LogLevel.ERROR, 0, "Points queue purged");
            }


        using (CDatabase db = Configuration.inst().GetDB())
        {
            if (!db.IsConnected())
            {
                m_bFlushing = false;
                m_Logger.Push(LogLevel.ERROR, 0, "Cant connect to db");
                return;
            }

            if (m_Queue.Count > 0)
            {
                try
                {
                    using (MySqlCommand cmdUpdate = new MySqlCommand("UPDATE curpos SET Time=?Time, Lat=?Lat, Lng=?Lng, Status=?Status, Speed=?Speed, Alt=?Alt, IO=?IO, GSMInfo=?GSMInfo WHERE TrackerID = ?ID AND Time <= ?Time", db.connection))
                        using (MySqlCommand cmdUpdate1 = new MySqlCommand("UPDATE lastpoint SET Time=?Time, Lat=?Lat, Lng=?Lng, Status=?Status, Speed=?Speed, Alt=?Alt, IO=?IO, GSMInfo=?GSMInfo WHERE TrackerID = ?ID AND Time <= ?Time", db.connection))
                            using (MySqlCommand cmdInsert = new MySqlCommand("INSERT INTO points(TrackerID, Time, Lat, Lng, Status, Speed, Alt, IO, GSMInfo,ForwardTime,ReceivedTime) VALUES(?ID, ?Time, ?Lat, ?Lng, ?Status, ?Speed, ?Alt, ?IO, ?GSMInfo,0," + CTime.GetTime(DateTime.UtcNow) + ") ON DUPLICATE KEY UPDATE TrackerID=TrackerID", db.connection))
                            {
                                cmdUpdate.Parameters.Add("?ID", MySqlDbType.Int32);     cmdInsert.Parameters.Add("?ID", MySqlDbType.Int32);
                                cmdUpdate.Parameters.Add("?Time", MySqlDbType.Int32);   cmdInsert.Parameters.Add("?Time", MySqlDbType.Int32);
                                cmdUpdate.Parameters.Add("?Lat", MySqlDbType.Float);    cmdInsert.Parameters.Add("?Lat", MySqlDbType.Float);
                                cmdUpdate.Parameters.Add("?Lng", MySqlDbType.Float);    cmdInsert.Parameters.Add("?Lng", MySqlDbType.Float);
                                cmdUpdate.Parameters.Add("?Alt", MySqlDbType.Int32);    cmdInsert.Parameters.Add("?Alt", MySqlDbType.Int32);
                                cmdUpdate.Parameters.Add("?Speed", MySqlDbType.Int32);  cmdInsert.Parameters.Add("?Speed", MySqlDbType.Int32);
                                cmdUpdate.Parameters.Add("?Status", MySqlDbType.Int32); cmdInsert.Parameters.Add("?Status", MySqlDbType.Int32);
                                cmdUpdate.Parameters.Add("?IO", MySqlDbType.Blob);      cmdInsert.Parameters.Add("?IO", MySqlDbType.Blob);
                                cmdUpdate.Parameters.Add("?GSMInfo", MySqlDbType.UInt64); cmdInsert.Parameters.Add("?GSMInfo", MySqlDbType.UInt64);
                                cmdUpdate1.Parameters.Add("?ID", MySqlDbType.Int32);
                                cmdUpdate1.Parameters.Add("?Time", MySqlDbType.Int32);
                                cmdUpdate1.Parameters.Add("?Lat", MySqlDbType.Float);
                                cmdUpdate1.Parameters.Add("?Lng", MySqlDbType.Float);
                                cmdUpdate1.Parameters.Add("?Alt", MySqlDbType.Int32);
                                cmdUpdate1.Parameters.Add("?Speed", MySqlDbType.Int32);
                                cmdUpdate1.Parameters.Add("?Status", MySqlDbType.Int32);
                                cmdUpdate1.Parameters.Add("?IO", MySqlDbType.Blob);
                                cmdUpdate1.Parameters.Add("?GSMInfo", MySqlDbType.UInt64);

                                using (MySqlTransaction trans = db.connection.BeginTransaction())
                                {
                                    while (true)
                                    {
                                        lock (m_Queue)
                                            if (m_Queue.Count > 0)
                                            {
                                                TrackerPacket point = m_Queue.Dequeue();
                                                if (point.IsFixed(true) && !point.Write2DB(cmdUpdate))
                                                {
                                                    break;
                                                }
                                                if (!point.Write2DB(cmdInsert))
                                                {
                                                    break;
                                                }
                                                if (!point.Write2DB(cmdUpdate1))
                                                {
                                                    break;
                                                }
                                            }
                                            else
                                            {
                                                break;
                                            }
                                    }
                                    trans.Commit();
                                }
                            }
                }
                catch (Exception e)
                {
                    m_Logger.Push(LogLevel.ERROR, 0, "Points " + e.ToString());
                }
            }
            //online режим
            try
            {
                using (MySqlTransaction trans = db.connection.BeginTransaction())
                {
                    using (MySqlCommand cmd1 = new MySqlCommand("UPDATE curpos SET online = 0", db.connection))
                        cmd1.ExecuteNonQuery();

                    using (MySqlCommand cmd = new MySqlCommand("UPDATE curpos SET online = 1 WHERE TrackerID = ?ID", db.connection))
                    {
                        cmd.Parameters.Add("?ID", MySqlDbType.Int32);

                        lock (m_SessionTrackers)
                            foreach (KeyValuePair <uint, long> value in m_SessionTrackers)
                            {
                                cmd.Parameters["?ID"].Value = value.Value;
                                cmd.ExecuteNonQuery();
                            }
                    }
                    trans.Commit();
                }
            }
            catch (Exception e)
            {
                m_Logger.Push(LogLevel.ERROR, 0, "Events " + e.ToString());
            }
        }
        GC.Collect();
        m_bFlushing = false;
    }
Beispiel #24
0
    protected void Tick(object obj)
    {
        int cnt = 0;

        if (m_bRunning)
        {
            return;
        }

        m_bRunning = true;
        try
        {
            m_Tracker = m_config.GetNextTracker();
            if (m_Tracker == null)
            {
                m_bRunning = false;
                return;
            }
            TrackerPacketList pts;
            DateTime          start = DateTime.UtcNow;
            using (CDatabase db = Configuration.inst().GetDB()) {
                pts = GetPoint(db);
                if (pts != null && pts.Count > 0)
                {
                    DateTime query = DateTime.UtcNow;
                    DateTime dt    = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                    dt = dt.AddTicks(pts[0].m_Time * 10000000);
                    if (dt <= System.DateTime.UtcNow)
                    {
                        cnt = DoSession(pts);
                    }
                    DateTime delete = DateTime.UtcNow;
                    if (cnt == pts.Count && DeletePoint(db, pts))
                    {
                        m_Logger.Push(LogLevel.INFO, 0, cnt + " point sent of " + pts.Count +
                                      ".Times for query/session/delete:" + (query - start).TotalMilliseconds + "/" + (delete - query).TotalMilliseconds + "/" + (DateTime.UtcNow - delete).TotalMilliseconds);
                        m_LastFailTime = 0;
                    }
                    if (cnt == 0 && m_LastFailTime == 0)
                    {
                        m_LastFailTime = CTime.GetTime(DateTime.UtcNow);
                    }
                }
                insertRecord(db, pts);
            }
        }
        catch (Exception ex)
        {
            m_Logger.Push(LogLevel.ERROR, 0, m_Tracker.m_IMEI + " Error sending points " + ex.ToString());
            if (m_LastFailTime == 0)
            {
                m_LastFailTime = CTime.GetTime(DateTime.UtcNow);
            }
        }
        try
        {
            if (m_LastFailTime > 0 && CTime.GetTime(DateTime.UtcNow) > m_LastFailTime + m_config.MaxFailTimeBeforeEmail)
            {
                m_LastFailTime = -1;
                EmailSender.inst().AddMessage(m_config.EmailAddr, m_config.EmailContent);
            }
        }
        catch (Exception ex)
        {
            m_Logger.Push(LogLevel.ERROR, 0, m_Tracker.m_IMEI + " Error in connection " + ex.ToString());
        }
        m_bRunning = false;
    }
Beispiel #25
0
    static void Log2DB(string filename, long IMEI)
    {
        Configuration.inst().Events = false;
        DateTime from = (new DateTime(2016, 11, 01, 11, 30, 0)).ToUniversalTime();
        //DateTime till = (new DateTime(2014, 01, 20, 15, 00, 0)).ToUniversalTime();

        int iFrom = CTime.GetTime(from); //0;
        int iTill = int.MaxValue;        // CTime.GetTime(till);

        int cnt = 0;

        Thread.Sleep(10000);
        StreamReader reader = new StreamReader(filename);

        while (!reader.EndOfStream)
        {
            string        str    = reader.ReadLine();
            TrackerPacket packet = new TrackerPacket(0);
            if (packet.TryParse(str))
            {
                if ((cnt++) % 1000 == 0)
                {
                    Console.WriteLine(cnt + " " + str);
                }

                if (IMEI != 0 && packet.m_ID != IMEI)
                {
                    continue;
                }

                if (packet.m_Time < iFrom || packet.m_Time > iTill)
                {
                    continue;
                }

                GPSPointQueue.inst().PushPacket(packet);
                if (packet.m_Time < CTime.GetTime(DateTime.UtcNow.AddMinutes(-3)) && packet.m_Speed > 0)
                {
                    try {
                        using (CDatabase db = Configuration.inst().GetDB()){
                            using (MySqlCommand cmdSelect = new MySqlCommand("Select Name,Comment From Trackers where IMEI='" + IMEI + "'", db.connection))
                            {
                                MySqlDataReader mdr      = cmdSelect.ExecuteReader();
                                Logger          m_Logger = new Logger();
                                EmailSender.inst().SetLogger(m_Logger.GetQueue("Email"));
                                EmailSender.inst().AddMessage("*****@*****.**", mdr.GetString(0) + " from " + mdr.GetString(1) + " more than 3 minutes network delay", "Device With IMEI No. " + IMEI + " And Vehicle No. " + mdr.GetString(0) + " Has Netweork Delayed More Than 3 Minutes As Its Latest Packet`s Date and Time Is " + CTime.GetTime(packet.m_Time).ToString("dd-MM-yyyy HH:mm:ss") + " And Speed Is " + packet.m_Speed);
                            }
                        }
                    }catch (Exception ex)
                    {
                        Console.Write("Email Has can't Be Sent " + ex.ToString());
                    }
                }
                Thread.Sleep(1);
            }
        }

        Thread.Sleep(30000);
        Global.m_Logger.FlushData();
        Console.WriteLine("Ready");
    }