Пример #1
0
        //public string ToInsertSQL(bool replaceComma, string TableName)
        //{
        //  string sql = "";
        //  sql = string.Format("insert into {0} (POS_FECHA, EQP_ESN, COD_EVENTO,", TableName);
        //  sql = string.Format("{0} POSICION, POS_VELOCIDAD, POS_RUMBO, DATA) VALUES (", sql);
        //  sql = string.Format("{0} '{1}', '{2}'", sql, ReportDate.ToString("yyyy-MM-dd HH:mm:ss"), IMEI);
        //  if (replaceComma)
        //    sql = string.Format("{0}, {1}, PointFromText('POINT({2} {3})')", sql, EventCode, ReportPosition.Longitude.getValue().ToString().Replace(',', '.'), ReportPosition.Latitude.getValue().ToString().Replace(',', '.'));
        //  else
        //    sql = string.Format("{0}, {1}, PointFromText('POINT({2} {3})')", sql, EventCode, ReportPosition.Longitude.getValue(), ReportPosition.Latitude.getValue());
        //  if (replaceComma)
        //    sql = string.Format("{0}, {1}, {2}", sql, Speed.ToString().Replace(',', '.'), ReportPosition.Head.ToString().Replace(',', '.'));
        //  else
        //    sql = string.Format("{0}, {1}, {2}", sql, Speed, ReportPosition.Head);
        //  sql = string.Format("{0},'{1}')", sql, JsonConvert.SerializeObject(Data));
        //  return sql;
        //}
        public static bool TryParse(byte[] messageSBD, string imei, out IridiumExtremeBinaryReport report, string packetType)
        {
            int ival;
              double dval;

              report = new IridiumExtremeBinaryReport();
              JObject json = new JObject();
              try
              {
            if (packetType == "MO")
            {
              ICDMOPacket MOpacket = new ICDMOPacket();
              ICDMOPacket.TryParse(messageSBD, out MOpacket);
              ICDMOMessageType type = ICDMOMessageType.Unknown;
              if (MOpacket.rheader != null)
              {
            report.IMEI = imei;
            report.protocolType = (int)MOpacket.rheader.protocolType;
            report.protocolVersion = (int)MOpacket.rheader.ProtocolVersionNumber;
            report.EventCode = (int)MOpacket.rheader.MessageType;
            report.type_message = packetType;
            type = MOpacket.rheader.MessageType;
              }
              else
              {
            report.IMEI = imei;
            report.protocolType = (int)MOpacket.header.protocolType;
            report.protocolVersion = (int)MOpacket.header.ProtocolVersionNumber;
            report.EventCode = (int)MOpacket.header.MessageType;
            report.type_message = packetType;
            type = MOpacket.header.MessageType;
              }
              switch (type)
              {
            case ICDMOMessageType.SwitchOn:
              report.inbox = true;
              break;
            case ICDMOMessageType.AutomaticPositionReport:
              report.inbox = true;
              report.posiciones = true;
              break;
            case ICDMOMessageType.Emergency:
              report.inbox = true;
              report.posiciones = true;
              break;
              }
              foreach (ICDDataBlock d in MOpacket.body.datablocks)
              {
            switch (d.BlockType)
            {
              case ICDBlockType.Location://automatic report position
                var location = (DataBlock_Location)d;
                report.ReportPosition = location.position;
                DateTime dt;
                try
                {
                 dt = new DateTime((int)location.GPSTimestampUTCYear, (int)location.GPSTimestampUTCMonth, (int)location.GPSTimestampUTCDay, (int)location.GPSTimestampUTCHours, (int)location.GPSTimestampUTCMinutes, (int)location.GPSTimestampUTCSeconds);
                 report.ReportDate = dt;
                }
                catch (Exception ex)
                {
                  report.ReportDate = new DateTime();//DateTime.Now;
                }
                report.Speed = 0;

                //string json5 = new JavaScriptSerializer().Serialize(location);
                //JObject json = JObject.FromObject(location);
                json["Location"] = JObject.FromObject(new {
                  Type = location.BlockType.ToString(),
                  DateTime = report.ReportDate,
                  VelocityDirection = location.VelocityDirection,
                  SpeedOverGround = location.SpeedOverGround,
                  CourseOverGround = location.CourseOverGround,
                  AltitudeSign = location.AltitudeSign,
                  Altitude = location.Altitude,
                  LatitudeAccuracyMeasurement = location.LatitudeAccuracyMeasurement,
                  LatitudeAccuracy = location.LatitudeAccuracy,
                  LongitudeAccuracyMeasurement = location.LongitudeAccuracyMeasurement,
                  LongitudeAccuracy =  location.LongitudeAccuracy,
                  AltitudeAccuracyMeasurement = location.AltitudeAccuracyMeasurement,
                  AltitudeAccuracy = location.AltitudeAccuracy,
                  IsValid = 1,
                  InsertInPosiciones = report.insertInPosiciones
                });
                json["Location"]["Position"] = JObject.FromObject(new {
                  Altitude = location.position.Altitude,
                  Longitude = location.position.Longitude,
                  Latitude = location.position.Latitude,
                  Cuadrante = location.position.Cuadrante,
                  Rumbo = location.position.Head
                });

                //DataBlock_Location fromJson = new JavaScriptSerializer().Deserialize<DataBlock_Location>(json);
                //var loc = new JavaScriptSerializer().DeserializeObject(json);
                //JObject jobject = JObject.Parse(json);//magic

                //var name = new{ Datablock = new []{ new {type = location.BlockType.ToString()}}};
                //JObject namejson = JObject.FromObject(name);
                //string json2 = string.Format("Datablock: {0} {3} : {4}{1} {5}{2}", "{", location.BlockType.ToString(), "}", "'type'", "'", "'");
                //JObject namejson = JObject.Parse(json2);
                //string a = @"{'type':"+"'"+location.BlockType.ToString()+"'"+"}";
                break;
              case ICDBlockType.FreeText:
                var freetext = (DataBlock_FreeText)d;
                json["FreeText"] = JObject.FromObject(new
                {
                  FreeText = freetext.FreeText.Text.ToString(),
                });
                break;
              case ICDBlockType.Recipient:
                var recipient = (DataBlock_Recipient)d;

                break;
              case ICDBlockType.Synchronisation:
                var synchronisation = (DataBlock_Synchronisation)d;
                break;
              case ICDBlockType.DeviceIdentifier:
                var deviceIdentifier = (DataBlock_DeviceIdentifier)d;
                break;
              case ICDBlockType.Diagnostics:
                var diagnostics = (DataBlock_Diagnostics)d;
                break;
              case ICDBlockType.Sender:
                var sender = (DataBlock_Sender)d;
                break;
              case ICDBlockType.RegionCircle:
                var regionCircle = (DataBlock_Circle)d;
                break;
              case ICDBlockType.RegionPolygon:
                var regionPolygon = (DataBlock_Polygon)d;
                break;
              case ICDBlockType.PortalStatus:
                var portalStatus = (DataBlock_PortalStatus)d;
                break;
              case ICDBlockType.PhoneSettings:
                var phoneSettings = (DataBlock_PhoneSettings)d;
                json["PhoneSettings"] = JObject.FromObject(new
                {
                  Type = phoneSettings.BlockType.ToString(),
                  DateTime = report.ReportDate,
                  ReportFrecuencyRate = phoneSettings.ReportingFrecuencyRate,
                  ReportingFrecuencyRateUnits = phoneSettings.ReportingFrecuencyRateUnits,
                  EmergencyDestination = phoneSettings.EmergencyDestination,
                  EmergencyCallRecipient = phoneSettings.EmergencyCallRecipient,
                });
                //JObject jsonPhoneSettings = JObject.FromObject(phoneSettings);
                //report.Data.Add(jsonPhoneSettings);
                break;
              case ICDBlockType.GeofenceStatus:
                var geofenceStatus = (DataBlock_GeofenceStatus)d;
                break;
              case ICDBlockType.CannedMessagesHash:
                var cannedMessageHash = (DataBlock_CannedMessagesHash)d;
                json["CannedMessageHash"] = JObject.FromObject(new
                {
                  Type = cannedMessageHash.BlockType.ToString(),
                  Hash = cannedMessageHash.Hash,
                });
                //JObject jsonCannedMessageHash = JObject.FromObject(cannedMessageHash);
                //report.Data.Add(jsonCannedMessageHash);
                //JsonConvert.SerializeObject(report.Data);
                break;
              case ICDBlockType.PortalProviderInformation:
                var portalProviderInfo = (DataBlock_PortalProviderInformation)d;
                break;
              case ICDBlockType.ReducedSizeLocation:
                var reducedSizeLocation = (DataBlock_ReducedLocation)d;
                break;
              case ICDBlockType.CannedMessageIdentifier:
                var cannedMessageIdentifier = (DataBlock_CannedMessageIdentifier)d;
                break;
              case ICDBlockType.DistributionListHash:
                var distributionList = (DataBlock_DistributionListHash)d;
                break;
              case ICDBlockType.MessageIdentifier:
                var messageIdentifier = (DataBlock_MessageIdentifier)d;
                break;
              case ICDBlockType.FirmwareHardwareVersion:
                var firmwareHardware = (DataBlock_HandsetFwHwVersion)d;
                break;
            }

              }
              report.Data = json;
            }
            else
            {
              ICDMTPacket MTpacket = new ICDMTPacket();
              ICDMTPacket.TryParse(messageSBD, out MTpacket);
              ICDMTMessageType type = ICDMTMessageType.Unknown;
              if (MTpacket.header != null)
              {
            report.IMEI = imei;//chequear si esta registrado
            report.protocolType = (int)MTpacket.header.protocolType;
            report.protocolVersion = (int)MTpacket.header.ProtocolVersionNumber;
            report.EventCode = (int)MTpacket.header.MessageType;
            type = MTpacket.header.MessageType;
              }
              else
              {
            report.IMEI = imei;
            report.protocolType = (int)MTpacket.header.protocolType;
            report.protocolVersion = (int)MTpacket.header.ProtocolVersionNumber;
            report.EventCode = (int)MTpacket.header.MessageType;
            type = MTpacket.header.MessageType;
              }

              report.sent = true;
            }
            return true;
              }
              catch (Exception ex) { }
              return false;
        }
Пример #2
0
        //chequea la bandeja de entrada y envia los MT pertinentes
        public bool ProcessMessagesFromDataBase(out List<byte[]> msgs, out List<string> imeis, out List<string> filenames)
        {
            //Por acá tendría que estar un método que traiga registros de la base
              //JObject json = JObject.Parse(str);
              int idMessageLastMessage = 0;
              inserts.Clear();
              int idMessage = 0;
              DateTime inDatetime = new DateTime();
              string imei = "000000000000000";//"300215010568090";
              string type = "";
              ICDMOMessageType MO_MessageType = ICDMOMessageType.Unknown;
              ICDMTMessageType MT_MessageType = ICDMTMessageType.Unknown;
              int protocol = 0;
              int protocolVersion = 0;
              int messageIdentifier = 0;
              string jsonData = "";
              JObject json = new JObject();
              //JArray json = new JArray();
              //JObject obj = new JObject();

              ICDMTMessageType TypeOfMT = ICDMTMessageType.Unknown;//(ICDMTMessageType)10;
              SynchronisationDataType typeSynchro = SynchronisationDataType.EmergencyCallRecipient;//(SynchronisationDataType)6;

              byte[] msgBytes;
              msgs = new List<byte[]>();
              imeis = new List<string>();
              filenames = new List<string>();
              List<ICDDataBlock> datablocks = new List<ICDDataBlock>();
              Encoding unicode = Encoding.Unicode;
              Encoding utf8 = Encoding.UTF8;

              OdbcCommand comm;
              string sql = "";
              try
              {
            if (ConnectToDatabase(out comm))
            #region codigo
            {
              string TableName = config.getValue("tableinbox");
              //var cmd = conn.CreateCommand();
              sql = string.Format("select * from {0}", TableName);
              comm.CommandText = sql;
              OdbcDataReader queryResults = comm.ExecuteReader();

              while (queryResults.Read())
              {
            try { idMessage = queryResults.GetInt16(0); }
            catch (InvalidCastException) { }
            try { inDatetime = queryResults.GetDateTime(1); }
            catch (InvalidCastException) { }
            try { imei = queryResults.GetString(2); }
            catch (InvalidCastException) { }
            try { type = queryResults.GetString(3); }
            catch (InvalidCastException) { }
            if (type == "MO")
            {
              try { MO_MessageType = (ICDMOMessageType)queryResults.GetInt16(4); }
              catch (InvalidCastException) { }
            }
            else
            {
              try { MT_MessageType = (ICDMTMessageType)queryResults.GetInt16(4); }
              catch (InvalidCastException) { }
            }
            try { protocol = queryResults.GetInt16(5); }
            catch (InvalidCastException) { }
            try { protocolVersion = queryResults.GetInt16(6); }
            catch (InvalidCastException) { }
            try { messageIdentifier = queryResults.GetInt16(7); }
            catch (InvalidCastException) { }
            try
            {
              jsonData = queryResults.GetString(8);
              json = JObject.Parse(jsonData);
              //string b = RemoveSpecialCharacters(jsonData);
              //var dict = new JavaScriptSerializer().DeserializeObject(jsonData);
              //var obj = JsonConvert.SerializeObject(dict);
            }
            catch (InvalidCastException) { }
            bool MTFLAG = false;
            string result = "";
            bool registered = false;
            string loginState = GET("http://vdms5.tesacom.net/login.php?user_name=userapi&password=T3s@m321");
            string url = String.Format("http://vdms5.tesacom.net/abm/abm_equipos.php?oper=exists&ESN={0}&contentType=json", imei);
            string jsonExists = GET(url);
            try
            {
              JObject jData = new JObject();
              jData = JObject.Parse(jsonExists);
              foreach (JProperty jsonProperty in jData.Children().ToList())
              {
                if (jsonProperty.Name.ToString() == "success")
                {
                  result = jsonProperty.Value.ToString();
                  if (result == "true")
                  {
                    registered = true;
                  }
                  log.writeToLogFile(LogType.LOG_NOTICE, "Consultando API", "Se consultó si existía el equipo con IMEI{0} y el resultado es success:{1}", imei, jsonProperty.Value.ToString());
                }
              }
            }
            catch (Exception ex) { }

            if (type == "MO")
            {
              TypeOfMT = ICDMTMessageType.Unknown;

              switch (MO_MessageType)
              {
                case ICDMOMessageType.SwitchOn:

                  //chequear si esta registrado
                  if (registered)
                  {
                    imeis.Add(imei);
                    TypeOfMT = ICDMTMessageType.PortalStatusMessage;
                    IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport();
                    report.ReportDate = DateTime.Now;
                    report.IMEI = imei;
                    report.type_message = type;
                    report.EventCode = (int)MO_MessageType;
                    report.protocolType = protocol;
                    report.protocolVersion = protocolVersion;
                    report.idMessage = idMessage;
                    report.Data = json;

                    string tname = config.getConfigValue("databasesection", "tableoutbox", "tablename");
                    inserts.Add(report.ToInsertSQL(true, tname));
                    string tname2 = config.getConfigValue("databasesection", "tableinbox", "tablename");
                    inserts.Add(report.ToDeleteSQL(tname2, idMessage));
                  }
                  else { TypeOfMT = ICDMTMessageType.Unknown; }
                  break;
                case ICDMOMessageType.AutomaticPositionReport:
                  //chequear si esta registrado
                  if (registered)
                  {
                    imeis.Add(imei);
                    IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport();
                    report.ReportDate = DateTime.Now;
                    report.IMEI = imei;
                    report.type_message = type;
                    report.EventCode = (int)MO_MessageType;
                    report.protocolType = protocol;
                    report.protocolVersion = protocolVersion;
                    report.idMessage = idMessage;
                    report.Data = json;

                    string tname = config.getConfigValue("databasesection", "tableoutbox", "tablename");
                    inserts.Add(report.ToInsertSQL(true, tname));
                    string tname2 = config.getConfigValue("databasesection", "tableinbox", "tablename");
                    inserts.Add(report.ToDeleteSQL(tname2, idMessage));
                  }
                  else { TypeOfMT = ICDMTMessageType.Unknown; }
                  break;
                case ICDMOMessageType.ManualPositionReport:
                  if (registered)
                  {
                    imeis.Add(imei);
                    IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport();
                    report.ReportDate = DateTime.Now;
                    report.IMEI = imei;
                    report.type_message = type;
                    report.EventCode = (int)MO_MessageType;
                    report.protocolType = protocol;
                    report.protocolVersion = protocolVersion;
                    report.idMessage = idMessage;
                    report.Data = json;

                    string tname = config.getConfigValue("databasesection", "tableoutbox", "tablename");
                    inserts.Add(report.ToInsertSQL(true, tname));
                    string tname2 = config.getConfigValue("databasesection", "tableinbox", "tablename");
                    inserts.Add(report.ToDeleteSQL(tname2, idMessage));
                  }
                  else { TypeOfMT = ICDMTMessageType.Unknown; }
                  break;
                case ICDMOMessageType.Emergency:
                  if (registered)
                  {
                    imeis.Add(imei);
                    IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport();
                    report.ReportDate = DateTime.Now;
                    report.IMEI = imei;
                    report.type_message = type;
                    report.EventCode = (int)MO_MessageType;
                    report.protocolType = protocol;
                    report.protocolVersion = protocolVersion;
                    report.idMessage = idMessage;
                    report.Data = json;

                    string tname = config.getConfigValue("databasesection", "tableoutbox", "tablename");
                    inserts.Add(report.ToInsertSQL(true, tname));
                    string tname2 = config.getConfigValue("databasesection", "tableinbox", "tablename");
                    inserts.Add(report.ToDeleteSQL(tname2, idMessage));

                    string insertInPosiciones = "";
                    foreach (JProperty jsonObject in json.Children().ToList())
                    {
                      if (jsonObject.Name == "Location")
                      {
                        foreach (JObject location in jsonObject.Children().ToList())
                        {
                          foreach (JProperty property in location.Children().ToList())
                          {
                            if (property.Name.ToString() == "InsertInPosiciones")
                            {
                              insertInPosiciones = property.Value.ToString();
                            }
                          }
                        }
                      }
                    }

                    if (insertInPosiciones == "Si")
                    {
                      string tname3 = config.getConfigValue("databasesection", "tableposition", "tablename");
                      inserts.Add(report.ToInsertSQL(true, tname3));
                    }

                  }
                  break;
                case ICDMOMessageType.CheckIn:
                  if (registered)
                  {
                    imeis.Add(imei);
                    TypeOfMT = ICDMTMessageType.Unknown;
                    IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport();
                    report.ReportDate = DateTime.Now;
                    report.IMEI = imei;
                    report.type_message = type;
                    report.EventCode = (int)MO_MessageType;
                    report.protocolType = protocol;
                    report.protocolVersion = protocolVersion;
                    report.idMessage = idMessage;
                    report.Data = json;

                    string tname = config.getConfigValue("databasesection", "tableoutbox", "tablename");
                    inserts.Add(report.ToInsertSQL(true, tname));
                    string tname2 = config.getConfigValue("databasesection", "tableinbox", "tablename");
                    inserts.Add(report.ToDeleteSQL(tname2, idMessage));
                  }
                  else { TypeOfMT = ICDMTMessageType.Unknown; }
                  break;
                case ICDMOMessageType.DiagnosticsResponse:
                case ICDMOMessageType.BeginMonitoring:
                case ICDMOMessageType.Deregistration:
                case ICDMOMessageType.CannedMessageSend:
                case ICDMOMessageType.EmergencyCancel:
                case ICDMOMessageType.EndMonitoring:
                case ICDMOMessageType.GeofenceCrossedByDevice:
                case ICDMOMessageType.MessageAcknowledgement:
                case ICDMOMessageType.RequestDeviceIdentifierResponse:
                case ICDMOMessageType.ResponseToLocationPingRequest:
                case ICDMOMessageType.SynchronisingDataOverTheAir:
                case ICDMOMessageType.UserExtensions:
                case ICDMOMessageType.Unknown:
                  break;
              }

            }
            else
            {
              MTFLAG = true;

              switch (MT_MessageType)
              {
                case ICDMTMessageType.FreeText:

                  //chequear si esta registrado
                  if (registered)
                  {
                    imeis.Add(imei);
                    TypeOfMT = ICDMTMessageType.FreeText;

                    IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport();
                    report.ReportDate = DateTime.Now;
                    report.IMEI = imei;
                    report.type_message = type;
                    report.EventCode = (int)MT_MessageType;
                    report.protocolType = protocol;
                    report.protocolVersion = protocolVersion;
                    report.idMessage = idMessage;
                    report.messageIdentifier = messageIdentifier;
                    report.Data = json;

                    string tname = config.getConfigValue("databasesection", "tableoutbox", "tablename");
                    inserts.Add(report.ToInsertSQL(true, tname));
                  }
                  else { TypeOfMT = ICDMTMessageType.Unknown; }
                  break;
                case ICDMTMessageType.PortalStatusMessage:

                  //chequear si esta registrado
                  if (registered)
                  {
                    imeis.Add(imei);
                    TypeOfMT = ICDMTMessageType.PortalStatusMessage;
                    IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport();
                    report.ReportDate = DateTime.Now;
                    report.IMEI = imei;
                    report.type_message = type;
                    report.EventCode = (int)MT_MessageType;
                    report.protocolType = protocol;
                    report.protocolVersion = protocolVersion;
                    report.idMessage = idMessage;
                    report.Data = json;

                    string tname = config.getConfigValue("databasesection", "tableoutbox", "tablename");
                    inserts.Add(report.ToInsertSQL(true, tname));
                    string tname2 = config.getConfigValue("databasesection", "tableinbox", "tablename");
                    inserts.Add(report.ToDeleteSQL(tname2, idMessage));
                  }
                  else { TypeOfMT = ICDMTMessageType.Unknown; }
                  break;
              }
            }
            ICDMTPacket MTpacket = new ICDMTPacket();
            MTpacket.header = new ICDMTMessageStandardHeader();
            MTpacket.header.protocolType = 101;
            MTpacket.header.ProtocolVersionNumber = 2;
            switch (TypeOfMT)
            {
              case ICDMTMessageType.PortalStatusMessage:
                //List<JProperty> ps = json["portalstatus"].Children().cast<JProperty>().Tolist();
                //foreach (JProperty p in ps)
                //{
                //  string key = p.Name.ToString();
                //  string value = p.Name.ToString();
                //}
                IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport();
                MTpacket.header.messageType = 10;
                MTpacket.header.MessageType = (ICDMTMessageType)MTpacket.header.messageType;
                MTpacket.header.MessageIdentifier = 221;//0

                DataBlock_PortalStatus statusMessage = new DataBlock_PortalStatus();
                DataBlock_PortalProviderInformation portalProviderInformation = new DataBlock_PortalProviderInformation();
                //string msg;
                statusMessage.Status = 0;
                string msgStatus = "OK";
                string msgProviderInfo = "LBS Portal";
                if (MTFLAG)
                {
                  foreach (JProperty jsonObject in json.Children().ToList())
                  {
                    if (jsonObject.Name == "PortalStatus")
                    {
                      foreach (JObject portalstatus in jsonObject.Children().ToList())
                      {
                        foreach (JProperty property in portalstatus.Children().ToList())
                        {
                          if (property.Name.ToString() == "FreeText")
                          {
                            msgStatus = property.Value.ToString();
                          }
                          if (property.Name.ToString() == "Status")
                          {
                            statusMessage.Status = (uint)property.Value;
                          }
                        }
                      }
                    }
                    if (jsonObject.Name == "PortalProviderInformation")
                    {
                      foreach (JObject portalproviderinf in jsonObject.Children().ToList())
                      {
                        foreach (JProperty property in portalproviderinf.Children().ToList())
                        {
                          if (property.Name.ToString() == "FreeText")
                          {
                            msgProviderInfo = property.Value.ToString();
                          }
                        }
                      }
                    }
                  }
                }
                else
                {
                  //We will do it but like the data came from vdms
                  msgStatus = "OK";
                  statusMessage.Status = 0;
                  msgProviderInfo = "LBS Portal";
                  statusMessage.BlockType = ICDBlockType.PortalStatus;
                  portalProviderInformation.BlockType = ICDBlockType.PortalProviderInformation;

                  JObject jsonTemp = new JObject();

                  jsonTemp["PortalStatus"] = JObject.FromObject(new
                  {
                    Type = statusMessage.BlockType.ToString(),
                    FreeText = msgStatus,
                    Status = statusMessage.Status
                  });

                  jsonTemp["PortalProviderInformation"] = JObject.FromObject(new
                  {
                    Type = portalProviderInformation.BlockType.ToString(),
                    FreeText = msgStatus
                  });

                  json = jsonTemp;

                }
                //Finished to set the Portal status
                statusMessage.blockType = (int)ICDBlockType.PortalStatus;
                statusMessage.BlockType = ICDBlockType.PortalStatus;
                statusMessage.BlockLengthIndicator = 0;
                msgBytes = GetBytes(msgStatus);
                msgBytes = Encoding.Convert(unicode, utf8, msgBytes);
                statusMessage.FreeText = msgBytes;
                MTpacket.body.datablocks.Add(statusMessage);
                //Finished to set the Portal provider datablock
                portalProviderInformation.blockType = (int)ICDBlockType.PortalProviderInformation;
                portalProviderInformation.BlockType = ICDBlockType.PortalProviderInformation;
                portalProviderInformation.BlockLengthIndicator = 0;
                msgBytes = GetBytes(msgProviderInfo);
                msgBytes = Encoding.Convert(unicode, utf8, msgBytes);
                portalProviderInformation.FreeText = msgBytes;
                MTpacket.body.datablocks.Add(portalProviderInformation);

                msgs.Add(MTpacket.ToBytes());
                string type_Message = "MT";

                if (IridiumExtremeBinaryReport.TryParse(MTpacket.ToBytes(), imei, out report, type_Message))
                {
                  if (report.sent)
                  {
                    report.Data = json;
                    report.idMessage = idMessage;
                    report.messageIdentifier = (int)MTpacket.header.MessageIdentifier;
                    report.ReportDate = DateTime.Now;
                    report.attachmentFilename = string.Format("{0}.SBD", DateTime.Now.ToString("yyyyMMdd_HHmmss_fff"));
                    filenames.Add(report.attachmentFilename);

                    saveToDisck(MTpacket.ToBytes(), report.attachmentFilename, @"\MESSAGES_SENT");

                    string table = config.getConfigValue("databasesection", "tablesent", "tablename");
                    inserts.Add(report.ToInsertSQL(true, table));
                  }
                }
                break;
              case ICDMTMessageType.FreeText:

                MTpacket.header.messageType = 7;
                MTpacket.header.MessageType = (ICDMTMessageType)MTpacket.header.messageType;
                MTpacket.header.MessageIdentifier = 0;

                DataBlock_FreeText freeText = new DataBlock_FreeText();
                freeText.BlockType = ICDBlockType.FreeText;
                freeText.blockType = (int)ICDBlockType.FreeText;
                string msg = "Hola desde el portal";
                //PROBAR
                freeText.FreeText.Text = msg;//VER
                freeText.BlockLengthIndicator = 1;
                freeText.FreeText.DecodeTextIndicator = 0;
                freeText.BlockLengthBytes = (uint)(msg.Length);
                freeText.FreeText.FreeTextLengthIndicator = 0;//VER
                freeText.FreeText.FreeTextLength = (uint)(freeText.FreeText.BytesText.Length);
                freeText.FreeText.DecodeTextIndicator = 0;
                freeText.FreeText.DecodeTextLength = (uint)(msg.Length);

                MTpacket.body.datablocks.Add(freeText);

                DataBlock_Sender sender = new DataBlock_Sender();
                sender.BlockType = ICDBlockType.Sender;
                sender.blockType = (uint)ICDBlockType.Sender;
                sender.BlockLengthIndicator = 0;
                msg = "Portal";
                sender.BlockLengthBytes = (uint)(msg.Length + 2);
                msgBytes = GetBytes(msg);
                msgBytes = Encoding.Convert(unicode, utf8, msgBytes);
                sender.Sender = msgBytes;
                MTpacket.body.datablocks.Add(sender);
                msgs.Add(MTpacket.ToBytes());
                break;
              case ICDMTMessageType.GeofenceActivate:

                DataBlock_Polygon polygon = new DataBlock_Polygon();

                DataBlock_Circle circle = new DataBlock_Circle();

                break;
              case ICDMTMessageType.ConfirmedCheckIn:
              case ICDMTMessageType.DiagnosticRequest:
              case ICDMTMessageType.EmergencyAcknowledge:
              case ICDMTMessageType.EmergencyCancelRequest:
              case ICDMTMessageType.GeofenceCancel:
              case ICDMTMessageType.LocationPingRequest:
              case ICDMTMessageType.RequestDeviceIdentifier:
              case ICDMTMessageType.SystemTestResponseEndToEnd:
              case ICDMTMessageType.Reserved:
              case ICDMTMessageType.Unknown:
                break;
              case ICDMTMessageType.UserExtensions:
                break;
              case ICDMTMessageType.SynchroniseDataToDevice:

                MTpacket.header.messageType = (uint)ICDMTMessageType.SynchroniseDataToDevice;
                MTpacket.header.MessageType = (ICDMTMessageType)MTpacket.header.messageType;
                MTpacket.header.MessageIdentifier = 0;

                DataBlock_Synchronisation synchronisation = new DataBlock_Synchronisation();
                switch (typeSynchro)
                {
                  case SynchronisationDataType.DistributionlistClearAll:

                    DataBlock_SynchronisationDistributionList distListClearAll = new DataBlock_SynchronisationDistributionList();
                    distListClearAll.blockType = (int)ICDBlockType.Synchronisation;
                    distListClearAll.BlockType = ICDBlockType.Synchronisation;
                    distListClearAll.BlockLengthBytes = 1;
                    distListClearAll.dataType = (int)SynchronisationDataType.DistributionListClear;
                    distListClearAll.DataType = SynchronisationDataType.DistributionListClear;
                    synchronisation = distListClearAll;
                    MTpacket.body.datablocks.Add(synchronisation);
                    break;
                  case SynchronisationDataType.DistributionListAdd:

                    DataBlock_SynchronisationDistributionList syncDistListAdd = new DataBlock_SynchronisationDistributionList();
                    syncDistListAdd.blockType = (int)ICDBlockType.Synchronisation;
                    syncDistListAdd.BlockType = ICDBlockType.Synchronisation;
                    msg = "Work";
                    syncDistListAdd.BlockLengthBytes = (uint)(msg.Length + 2);
                    syncDistListAdd.dataType = (int)SynchronisationDataType.DistributionListAdd;
                    syncDistListAdd.DataType = SynchronisationDataType.DistributionListAdd;
                    msgBytes = GetBytes(msg);
                    msgBytes = Encoding.Convert(unicode, utf8, msgBytes);
                    DataBlock_DistributionList distList = new DataBlock_DistributionList();
                    distList.DistributionList = msgBytes;
                    syncDistListAdd.data = distList;
                    synchronisation = syncDistListAdd;
                    MTpacket.body.datablocks.Add(synchronisation);
                    break;
                  case SynchronisationDataType.DistributionListClear:

                    DataBlock_SynchronisationDistributionList syncDistListClear = new DataBlock_SynchronisationDistributionList();
                    syncDistListClear.blockType = (int)ICDBlockType.Synchronisation;
                    syncDistListClear.BlockType = ICDBlockType.Synchronisation;
                    msg = "Work";
                    syncDistListClear.BlockLengthBytes = (uint)(msg.Length + 2);
                    syncDistListClear.dataType = (int)SynchronisationDataType.DistributionListClear;
                    syncDistListClear.DataType = SynchronisationDataType.DistributionListClear;
                    msgBytes = GetBytes(msg);
                    msgBytes = Encoding.Convert(unicode, utf8, msgBytes);
                    DataBlock_DistributionList distListClear = new DataBlock_DistributionList();
                    distListClear.DistributionList = msgBytes;
                    syncDistListClear.data = distListClear;
                    synchronisation = syncDistListClear;
                    MTpacket.body.datablocks.Add(synchronisation);
                    break;
                  case SynchronisationDataType.CannedMessage:

                    DataBlock_SynchronisationCannedMessage syncCannedMsg = new DataBlock_SynchronisationCannedMessage();
                    syncCannedMsg.blockType = (int)ICDBlockType.Synchronisation;
                    syncCannedMsg.BlockType = ICDBlockType.Synchronisation;
                    msg = "I have achieved my objective";
                    syncCannedMsg.BlockLengthBytes = (uint)(msg.Length + 2);
                    syncCannedMsg.dataType = (int)SynchronisationDataType.CannedMessage;
                    syncCannedMsg.DataType = SynchronisationDataType.CannedMessage;
                    msgBytes = GetBytes(msg);
                    msgBytes = Encoding.Convert(unicode, utf8, msgBytes);

                    DataBlock_CannedMessageData cmd = new DataBlock_CannedMessageData();
                    cmd.LanguageIdentifier = "en";
                    cmd.LanguageIdentifierFirstLetter = (int)LettersIdentifier.e;
                    cmd.LanguageIdentifierSecondLetter = (int)LettersIdentifier.n;
                    cmd.CannedMessageNumber = 1;
                    cmd.IncludeLocation = 0;
                    cmd.CannedMessage = msgBytes;
                    syncCannedMsg.data = cmd;
                    synchronisation = syncCannedMsg;
                    MTpacket.body.datablocks.Add(synchronisation);
                    break;
                  case SynchronisationDataType.AddressBookEntry:
                    DataBlock_SynchronisationAddressBook syncAddressBook = new DataBlock_SynchronisationAddressBook();
                    syncAddressBook.blockType = (int)ICDBlockType.Synchronisation;
                    syncAddressBook.BlockType = ICDBlockType.Synchronisation;
                    msg = "addressBook";
                    syncAddressBook.BlockLengthBytes = (uint)(msg.Length + 2);
                    syncAddressBook.dataType = (int)SynchronisationDataType.AddressBookEntry;
                    syncAddressBook.DataType = SynchronisationDataType.AddressBookEntry;
                    msgBytes = GetBytes(msg);
                    msgBytes = Encoding.Convert(unicode, utf8, msgBytes);
                    DataBlock_AddressBook addressBook = new DataBlock_AddressBook();
                    addressBook.AddressBookNumber = (uint)100;
                    addressBook.BytesAddressBookItem = msgBytes;
                    syncAddressBook.data = addressBook;
                    synchronisation = syncAddressBook;
                    MTpacket.body.datablocks.Add(synchronisation);
                    //to complete
                    break;
                  case SynchronisationDataType.EmergencyCallRecipient:
                    DataBlock_SynchronisationEmergencyCallRecipient syncEmergCallRec = new DataBlock_SynchronisationEmergencyCallRecipient();
                    syncEmergCallRec.blockType = (int)ICDBlockType.Synchronisation;
                    syncEmergCallRec.BlockType = ICDBlockType.Synchronisation;
                    msg = "emergencycallrecipient";
                    syncEmergCallRec.BlockLengthBytes = (uint)(msg.Length + 2);
                    syncEmergCallRec.dataType = (int)SynchronisationDataType.EmergencyCallRecipient;
                    syncEmergCallRec.DataType = SynchronisationDataType.EmergencyCallRecipient;
                    msgBytes = GetBytes(msg);
                    msgBytes = Encoding.Convert(unicode, utf8, msgBytes);
                    DataBlock_EmergencyCallRecipient emerCallRec = new DataBlock_EmergencyCallRecipient();
                    emerCallRec.EmergencyCallRecipient = msgBytes;
                    syncEmergCallRec.data = emerCallRec;
                    synchronisation = syncEmergCallRec;
                    MTpacket.body.datablocks.Add(synchronisation);
                    //to complete
                    break;
                  case SynchronisationDataType.EmergencyDestination:
                    DataBlock_SynchronisationEmergencyDestination syncEmergDest = new DataBlock_SynchronisationEmergencyDestination();
                    syncEmergDest.blockType = (int)ICDBlockType.Synchronisation;
                    syncEmergDest.BlockType = ICDBlockType.Synchronisation;
                    syncEmergDest.dataType = (int)SynchronisationDataType.EmergencyDestination;
                    syncEmergDest.DataType = SynchronisationDataType.EmergencyDestination;
                    //to complete
                    break;
                  case SynchronisationDataType.GPSFrequencyRate:
                    DataBlock_SynchronisationReportingFrequencyRate repFreqRate = new DataBlock_SynchronisationReportingFrequencyRate();
                    //to complete
                    break;
                  case SynchronisationDataType.ProtocolType:
                    DataBlock_SynchronisationProtocolType protocolType = new DataBlock_SynchronisationProtocolType();
                    //to complete
                    break;
                }
                msgs.Add(MTpacket.ToBytes());
                break;
            }//termina switch principal
              }//termina while
              if (msgs.Count > 0)
              {
            return true;
              }
              else
              {
            return false;
              }
            }//termina if
            else
            {
              return false;
            }
            #endregion
              }
              catch (Exception ex)
              {
            log.writeToLogFile(LogType.LOG_NOTICE, "ConnectToDatabase", "Hubo un error: {0}, en la consulta: {1} ", ex.Message, sql);
            return false;
              }
        }
Пример #3
0
        public static bool TryParse(byte[] buff, int offset, ICDMTPacket packet1, out ICDMTPacket packet)
        {
            bool reslt = false;
              packet = packet1;
              packet.body = new ICDMTMessageBody();
              ICDMTMessageType type = ICDMTMessageType.Unknown;
              type = packet.header.MessageType;
              int boffset = offset;

              BitStream stream = new BitStream(buff);
              uint blockType = 0;
              if (boffset == 0)
              {
            boffset = ICDMTMessageStandardHeader.HeaderLen;
              }
              blockType = stream.GetUint(boffset, ICDDataBlock.BlockTypeLen);

              switch (type)
              {
            case ICDMTMessageType.EmergencyAcknowledge:
            case ICDMTMessageType.EmergencyCancelRequest:
            case ICDMTMessageType.LocationPingRequest:
            case ICDMTMessageType.SystemTestResponseEndToEnd:
            case ICDMTMessageType.DiagnosticRequest:
            case ICDMTMessageType.ConfirmedCheckIn:
            case ICDMTMessageType.GeofenceCancel:
            case ICDMTMessageType.RequestDeviceIdentifier:
              break;
            case ICDMTMessageType.FreeText:
              while (boffset < buff.Length * 8)
              {
            blockType = stream.GetUint(boffset, ICDDataBlock.BlockTypeLen);
            switch (blockType)
            {
              case 0x01:
                DataBlock_FreeText freeText;
                if (DataBlock_FreeText.TryParse(buff, boffset, out freeText))
                {
                  packet.body.datablocks.Add(freeText);
                  boffset += (int)freeText.FreeTextLenBytes * 8;
                }
                break;
              case 0x06:
                {
                  DataBlock_Sender sender;
                  if (DataBlock_Sender.TryParse(buff, boffset, out sender))
                  {
                    packet.body.datablocks.Add(sender);
                    boffset += (int)sender.SenderLenBytes * 8;
                  }
                }
                break;
            }
              }
              break;
            case ICDMTMessageType.GeofenceActivate:
              while (boffset < buff.Length * 8)
              {
            blockType = stream.GetUint(boffset, ICDDataBlock.BlockTypeLen);
            switch (blockType)
            {
              case 0x08:
                DataBlock_Polygon polygon;
                if (DataBlock_Polygon.TryParse(buff, boffset, out polygon))
                {
                  packet.body.datablocks.Add(polygon);
                  boffset += (int)polygon.BlockLengthBytes * 8;
                }
                break;
              case 0x07:
                DataBlock_Circle circle;
                if (DataBlock_Circle.TryParse(buff, boffset, out circle))
                {
                  packet.body.datablocks.Add(circle);
                  boffset += (int)circle.BlockLengthBytes * 8;
                }
                break;
            }
              }
              break;
            case ICDMTMessageType.SynchroniseDataToDevice:
              while (boffset < buff.Length * 8)
              {
            DataBlock_Synchronisation synchronisation;
            if (DataBlock_Synchronisation.TryParse(buff, boffset, out synchronisation))
            {
              packet.body.datablocks.Add(synchronisation);
              boffset += synchronisation.SynchronisationLenBytes * 8;
            }
              }
              break;
            case ICDMTMessageType.PortalStatusMessage:

              while (boffset < buff.Length * 8)
              {
            blockType = stream.GetUint(boffset, ICDDataBlock.BlockTypeLen);
            switch (blockType)
            {
              case 0x09:
                DataBlock_PortalStatus portalStatus;
                if (DataBlock_PortalStatus.TryParse(buff, boffset, out portalStatus))
                {
                  packet.body.datablocks.Add(portalStatus);
                  boffset += portalStatus.PortalStatusLenBytes * 8;
                }
                break;
              case 0x0d:
                DataBlock_PortalProviderInformation portalProviderInformation;
                if (DataBlock_PortalProviderInformation.TryParse(buff, boffset, out portalProviderInformation))
                {
                  packet.body.datablocks.Add(portalProviderInformation);
                  boffset += portalProviderInformation.PortalProviderInformationLenBytes * 8;
                }
                break;
            }
              }
              break;

            case ICDMTMessageType.Reserved://borrar?
              break;
            case ICDMTMessageType.UserExtensions: // borrar?
              break;
              }
              return reslt;
        }
Пример #4
0
        public static bool TryParse(byte[] buff, out ICDMTPacket packet)
        {
            bool reslt = false;
              packet = new ICDMTPacket();

              reslt = ICDMTMessageStandardHeader.TryParse(buff, 0, out packet.header);
              if (reslt)
              {
            reslt = ICDMTMessageBody.TryParse(buff, 0, packet, out packet);
              }

              return reslt;
        }
Пример #5
0
        //chequea la bandeja de entrada y envia los MT pertinentes
        public bool ProcessMessagesFromDataBase(out List<byte[]> msgs, out List<string> imeis, out List<string> filenames)
        {
            //Por acá tendría que estar un método que traiga registros de la base
              //JObject json = JObject.Parse(str);
              int idMessageLastMessage = 0;
              inserts.Clear();
              int idMessage = 0;
              DateTime inDatetime = new DateTime();
              string imei = "300215010568090";
              string type = "";
              ICDMOMessageType MO_MessageType = ICDMOMessageType.Unknown;
              ICDMTMessageType MT_MessageType = ICDMTMessageType.Unknown;
              int protocol = 0;
              int protocolVersion = 0;
              int messageIdentifier = 0;
              string jsonData = "";

              ICDMTMessageType TypeOfMT = ICDMTMessageType.Unknown;//(ICDMTMessageType)10;
              SynchronisationDataType typeSynchro = SynchronisationDataType.EmergencyCallRecipient;//(SynchronisationDataType)6;

              byte[] msgBytes;
              msgs = new List<byte[]>();
              imeis = new List<string>();
              filenames = new List<string>();
              List<ICDDataBlock> datablocks = new List<ICDDataBlock>();
              Encoding unicode = Encoding.Unicode;
              Encoding utf8 = Encoding.UTF8;

              OdbcCommand comm;
              string sql = "";
              try
              {
            if (ConnectToDatabase(out comm))
            #region codigo
            {
              string TableName = config.getValue("tableinbox");
              //var cmd = conn.CreateCommand();
              sql = string.Format("select * from {0}", TableName);
              comm.CommandText = sql;
              OdbcDataReader queryResults = comm.ExecuteReader();

              while (queryResults.Read())
              {
            try { idMessage = queryResults.GetInt16(0); }
            catch (InvalidCastException) { }
            try { inDatetime = queryResults.GetDateTime(1); }
            catch (InvalidCastException) { }
            try { imei = queryResults.GetString(2); }
            catch (InvalidCastException) { }
            try { type = queryResults.GetString(3); }
            catch (InvalidCastException) { }
            if(type == "MO")
            {
            try { MO_MessageType = (ICDMOMessageType)queryResults.GetInt16(4); }
            catch (InvalidCastException) { }
            }
            else
            {
            try { MT_MessageType = (ICDMTMessageType)queryResults.GetInt16(4); }
            catch (InvalidCastException) { }
            }
            try { protocol = queryResults.GetInt16(5); }
            catch (InvalidCastException) { }
            try { protocolVersion = queryResults.GetInt16(6); }
            catch (InvalidCastException) { }
            try { messageIdentifier = queryResults.GetInt16(7); }
            catch (InvalidCastException) { }
            try { jsonData = queryResults.GetString(8); }
            catch (InvalidCastException) { }

            if (type == "MO")
            {
              bool registered = true;
              TypeOfMT = ICDMTMessageType.Unknown;
              switch (MO_MessageType)
              {
                case ICDMOMessageType.SwitchOn:

                  //chequear si esta registrado
                  if (registered)
                  {
                    imeis.Add(imei);
                    TypeOfMT = ICDMTMessageType.PortalStatusMessage;
                    IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport();
                    report.ReportDate = DateTime.Now;
                    report.IMEI = imei;
                    report.type_message = type;
                    report.EventCode = (int)MO_MessageType;
                    report.protocolType = protocol;
                    report.protocolVersion = protocolVersion;
                    report.idMessage = idMessage;
                    report.jsonData = jsonData;

                    string tname = config.getConfigValue("databasesection", "tableoutbox", "tablename");
                    inserts.Add(report.ToInsertSQL(true, tname));

                    string tname2 = config.getConfigValue("databasesection", "tableinbox", "tablename");
                    inserts.Add(report.ToDeleteSQL(tname2, idMessage));
                  }
                  else { TypeOfMT = ICDMTMessageType.Unknown; }
                  break;
                case ICDMOMessageType.AutomaticPositionReport:
                  //chequear si esta registrado
                  if (registered)
                  {
                    imeis.Add(imei);
                    IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport();
                    report.ReportDate = DateTime.Now;
                    report.IMEI = imei;
                    report.type_message = type;
                    report.EventCode = (int)MO_MessageType;
                    report.protocolType = protocol;
                    report.protocolVersion = protocolVersion;
                    report.idMessage = idMessage;
                    report.jsonData = jsonData;

                    string tname = config.getConfigValue("databasesection", "tableoutbox", "tablename");
                    inserts.Add(report.ToInsertSQL(true, tname));
                    string tname2 = config.getConfigValue("databasesection", "tableinbox", "tablename");
                    inserts.Add(report.ToDeleteSQL(tname2, idMessage));
                  }
                  else { TypeOfMT = ICDMTMessageType.Unknown; }
                  break;
                case ICDMOMessageType.ManualPositionReport:
                  if (registered)
                  {
                    imeis.Add(imei);
                    IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport();
                    report.ReportDate = DateTime.Now;
                    report.IMEI = imei;
                    report.type_message = type;
                    report.EventCode = (int)MO_MessageType;
                    report.protocolType = protocol;
                    report.protocolVersion = protocolVersion;
                    report.idMessage = idMessage;
                    report.jsonData = jsonData;

                    string tname = config.getConfigValue("databasesection", "tableoutbox", "tablename");
                    inserts.Add(report.ToInsertSQL(true, tname));
                    string tname2 = config.getConfigValue("databasesection", "tableinbox", "tablename");
                    inserts.Add(report.ToDeleteSQL(tname2, idMessage));
                  }
                  else { TypeOfMT = ICDMTMessageType.Unknown; }
                  break;
                case ICDMOMessageType.Emergency:
                  if (registered)
                  {
                    imeis.Add(imei);
                    IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport();
                    report.ReportDate = DateTime.Now;
                    report.IMEI = imei;
                    report.type_message = type;
                    report.EventCode = (int)MO_MessageType;
                    report.protocolType = protocol;
                    report.protocolVersion = protocolVersion;
                    report.idMessage = idMessage;
                    report.jsonData = jsonData;

                    string tname = config.getConfigValue("databasesection", "tableoutbox", "tablename");
                    inserts.Add(report.ToInsertSQL(true, tname));
                    string tname2 = config.getConfigValue("databasesection", "tableinbox", "tablename");
                    inserts.Add(report.ToDeleteSQL(tname2, idMessage));
                  }
                  break;
                case ICDMOMessageType.CheckIn:
                  break;
              }

            }
            else
            {
              switch (MT_MessageType)
              {
                case ICDMTMessageType.FreeText:
                  bool registered = true;
                  //chequear si esta registrado
                  if (registered)
                  {
                    imeis.Add(imei);
                    TypeOfMT = ICDMTMessageType.FreeText;

                    IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport();
                    report.ReportDate = DateTime.Now;
                    report.IMEI = imei;
                    report.type_message = type;
                    report.EventCode = (int)MT_MessageType;
                    report.protocolType = protocol;
                    report.protocolVersion = protocolVersion;
                    report.idMessage = idMessage;
                    report.messageIdentifier = messageIdentifier;
                    report.jsonData = jsonData;

                    string tname = config.getConfigValue("databasesection", "tableoutbox", "tablename");
                    inserts.Add(report.ToInsertSQL(true, tname));
                  }
                  else { TypeOfMT = ICDMTMessageType.Unknown; }
                  break;
              }
            }
            ICDMTPacket MTpacket = new ICDMTPacket();
            MTpacket.header = new ICDMTMessageStandardHeader();
            MTpacket.header.protocolType = 101;
            MTpacket.header.ProtocolVersionNumber = 2;
            switch (TypeOfMT)
            {
              case ICDMTMessageType.PortalStatusMessage://complementar

                IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport();
                MTpacket.header.messageType = 10;
                MTpacket.header.MessageType = (ICDMTMessageType)MTpacket.header.messageType;
                MTpacket.header.MessageIdentifier = 221;//0

                DataBlock_PortalStatus statusMessage = new DataBlock_PortalStatus();
                statusMessage.blockType = (int)ICDBlockType.PortalStatus;
                statusMessage.BlockType = ICDBlockType.PortalStatus;
                statusMessage.BlockLengthIndicator = 0;
                statusMessage.Status = 0;
                string msg;
                msg = "OK";
                msgBytes = GetBytes(msg);
                msgBytes = Encoding.Convert(unicode, utf8, msgBytes);
                statusMessage.FreeText = msgBytes;
                MTpacket.body.datablocks.Add(statusMessage);
                JObject json1 = JObject.FromObject(statusMessage);
                json1.Add("Type", statusMessage.BlockType.ToString());
                json1.Add("FreeText", statusMessage.FreeTextLengthAndFreeTextString);
                json1.Add("Status", statusMessage.Status);

                DataBlock_PortalProviderInformation portalProviderInformation = new DataBlock_PortalProviderInformation();
                portalProviderInformation.blockType = (int)ICDBlockType.PortalProviderInformation;
                portalProviderInformation.BlockType = ICDBlockType.PortalProviderInformation;
                portalProviderInformation.BlockLengthIndicator = 0;
                msg = "LBS Portal";
                msgBytes = GetBytes(msg);
                msgBytes = Encoding.Convert(unicode, utf8, msgBytes);
                portalProviderInformation.FreeText = msgBytes;
                MTpacket.body.datablocks.Add(portalProviderInformation);
                msgs.Add(MTpacket.ToBytes());
                JObject json2 = JObject.FromObject(portalProviderInformation);
                json2.Add("Type", portalProviderInformation.BlockType.ToString());
                json2.Add("FreeText", portalProviderInformation.LengthAndFreeTextString);

                string type_Message = "MT";
                if (IridiumExtremeBinaryReport.TryParse(MTpacket.ToBytes(), imei, out report, type_Message ))
                {
                  if (report.sent)
                  {
                    report.Data.Add(json1);
                    report.Data.Add(json2);
                    //report.idMessage = report.idMessage = idMessage;
                    report.idMessage = idMessage;
                    report.messageIdentifier = (int)MTpacket.header.MessageIdentifier;
                    report.ReportDate = DateTime.Now;
                    report.attachmentFilename = string.Format("{0}.SBD", DateTime.Now.ToString("yyyyMMdd_HHmmss_fff"));
                    filenames.Add(report.attachmentFilename);

                    saveToDisck(MTpacket.ToBytes(), report.attachmentFilename, @"\MESSAGES_SENT");

                    string table = config.getConfigValue("databasesection", "tablesent", "tablename");
                    inserts.Add(report.ToInsertSQL(true, table));
                  }
                }
                break;
              case ICDMTMessageType.FreeText:

                MTpacket.header.messageType = 7;
                MTpacket.header.MessageType = (ICDMTMessageType)MTpacket.header.messageType;
                MTpacket.header.MessageIdentifier = 0;

                DataBlock_FreeText freeText = new DataBlock_FreeText();
                freeText.BlockType = ICDBlockType.FreeText;
                freeText.blockType = (int)ICDBlockType.FreeText;
                msg = "Hola desde el portal";
                //PROBAR
                freeText.FreeText.Text = msg;//VER
                freeText.BlockLengthIndicator = 1;
                freeText.FreeText.DecodeTextIndicator = 0;
                freeText.BlockLengthBytes = (uint)(msg.Length);
                freeText.FreeText.FreeTextLengthIndicator = 0;//VER
                freeText.FreeText.FreeTextLength = (uint)(freeText.FreeText.BytesText.Length);
                freeText.FreeText.DecodeTextIndicator = 0;
                freeText.FreeText.DecodeTextLength = (uint)(msg.Length);

                MTpacket.body.datablocks.Add(freeText);

                DataBlock_Sender sender = new DataBlock_Sender();
                sender.BlockType = ICDBlockType.Sender;
                sender.blockType = (uint)ICDBlockType.Sender;
                sender.BlockLengthIndicator = 0;
                msg = "Portal";
                sender.BlockLengthBytes = (uint)(msg.Length + 2);
                msgBytes = GetBytes(msg);
                msgBytes = Encoding.Convert(unicode, utf8, msgBytes);
                sender.Sender = msgBytes;
                MTpacket.body.datablocks.Add(sender);
                msgs.Add(MTpacket.ToBytes());
                break;
              case ICDMTMessageType.GeofenceActivate:

                DataBlock_Polygon polygon = new DataBlock_Polygon();

                DataBlock_Circle circle = new DataBlock_Circle();

                break;
              case ICDMTMessageType.ConfirmedCheckIn:
              case ICDMTMessageType.DiagnosticRequest:
              case ICDMTMessageType.EmergencyAcknowledge:
              case ICDMTMessageType.EmergencyCancelRequest:
              case ICDMTMessageType.GeofenceCancel:
              case ICDMTMessageType.LocationPingRequest:
              case ICDMTMessageType.RequestDeviceIdentifier:
              case ICDMTMessageType.SystemTestResponseEndToEnd:
              case ICDMTMessageType.Reserved:
              case ICDMTMessageType.Unknown:
                break;
              case ICDMTMessageType.UserExtensions:
                break;
              case ICDMTMessageType.SynchroniseDataToDevice:

                MTpacket.header.messageType = (uint)ICDMTMessageType.SynchroniseDataToDevice;
                MTpacket.header.MessageType = (ICDMTMessageType)MTpacket.header.messageType;
                MTpacket.header.MessageIdentifier = 0;

                DataBlock_Synchronisation synchronisation = new DataBlock_Synchronisation();
                switch (typeSynchro)
                {
                  case SynchronisationDataType.DistributionlistClearAll:

                    DataBlock_SynchronisationDistributionList distListClearAll = new DataBlock_SynchronisationDistributionList();
                    distListClearAll.blockType = (int)ICDBlockType.Synchronisation;
                    distListClearAll.BlockType = ICDBlockType.Synchronisation;
                    distListClearAll.BlockLengthBytes = 1;
                    distListClearAll.dataType = (int)SynchronisationDataType.DistributionListClear;
                    distListClearAll.DataType = SynchronisationDataType.DistributionListClear;
                    synchronisation = distListClearAll;
                    MTpacket.body.datablocks.Add(synchronisation);
                    break;
                  case SynchronisationDataType.DistributionListAdd:

                    DataBlock_SynchronisationDistributionList syncDistListAdd = new DataBlock_SynchronisationDistributionList();
                    syncDistListAdd.blockType = (int)ICDBlockType.Synchronisation;
                    syncDistListAdd.BlockType = ICDBlockType.Synchronisation;
                    msg = "Work";
                    syncDistListAdd.BlockLengthBytes = (uint)(msg.Length + 2);
                    syncDistListAdd.dataType = (int)SynchronisationDataType.DistributionListAdd;
                    syncDistListAdd.DataType = SynchronisationDataType.DistributionListAdd;
                    msgBytes = GetBytes(msg);
                    msgBytes = Encoding.Convert(unicode, utf8, msgBytes);
                    DataBlock_DistributionList distList = new DataBlock_DistributionList();
                    distList.DistributionList = msgBytes;
                    syncDistListAdd.data = distList;
                    synchronisation = syncDistListAdd;
                    MTpacket.body.datablocks.Add(synchronisation);
                    break;
                  case SynchronisationDataType.DistributionListClear:

                    DataBlock_SynchronisationDistributionList syncDistListClear = new DataBlock_SynchronisationDistributionList();
                    syncDistListClear.blockType = (int)ICDBlockType.Synchronisation;
                    syncDistListClear.BlockType = ICDBlockType.Synchronisation;
                    msg = "Work";
                    syncDistListClear.BlockLengthBytes = (uint)(msg.Length + 2);
                    syncDistListClear.dataType = (int)SynchronisationDataType.DistributionListClear;
                    syncDistListClear.DataType = SynchronisationDataType.DistributionListClear;
                    msgBytes = GetBytes(msg);
                    msgBytes = Encoding.Convert(unicode, utf8, msgBytes);
                    DataBlock_DistributionList distListClear = new DataBlock_DistributionList();
                    distListClear.DistributionList = msgBytes;
                    syncDistListClear.data = distListClear;
                    synchronisation = syncDistListClear;
                    MTpacket.body.datablocks.Add(synchronisation);
                    break;
                  case SynchronisationDataType.CannedMessage:

                    DataBlock_SynchronisationCannedMessage syncCannedMsg = new DataBlock_SynchronisationCannedMessage();
                    syncCannedMsg.blockType = (int)ICDBlockType.Synchronisation;
                    syncCannedMsg.BlockType = ICDBlockType.Synchronisation;
                    msg = "I have achieved my objective";
                    syncCannedMsg.BlockLengthBytes = (uint)(msg.Length + 2);
                    syncCannedMsg.dataType = (int)SynchronisationDataType.CannedMessage;
                    syncCannedMsg.DataType = SynchronisationDataType.CannedMessage;
                    msgBytes = GetBytes(msg);
                    msgBytes = Encoding.Convert(unicode, utf8, msgBytes);
                    DataBlock_CannedMessageData cmd = new DataBlock_CannedMessageData();

                    cmd.LanguageIdentifier = "en";
                    cmd.LanguageIdentifierFirstLetter = (int)LettersIdentifier.e;
                    cmd.LanguageIdentifierSecondLetter = (int)LettersIdentifier.n;
                    cmd.CannedMessageNumber = 1;
                    cmd.IncludeLocation = 0;
                    cmd.CannedMessage = msgBytes;
                    syncCannedMsg.data = cmd;
                    synchronisation = syncCannedMsg;
                    MTpacket.body.datablocks.Add(synchronisation);
                    break;
                  case SynchronisationDataType.AddressBookEntry:
                    DataBlock_SynchronisationAddressBook syncAddressBook = new DataBlock_SynchronisationAddressBook();
                    syncAddressBook.blockType = (int)ICDBlockType.Synchronisation;
                    syncAddressBook.BlockType = ICDBlockType.Synchronisation;
                    msg = "addressBook";
                    syncAddressBook.BlockLengthBytes = (uint)(msg.Length + 2);
                    syncAddressBook.dataType = (int)SynchronisationDataType.AddressBookEntry;
                    syncAddressBook.DataType = SynchronisationDataType.AddressBookEntry;
                    msgBytes = GetBytes(msg);
                    msgBytes = Encoding.Convert(unicode, utf8, msgBytes);
                    DataBlock_AddressBook addressBook = new DataBlock_AddressBook();
                    addressBook.AddressBookNumber = (uint)100;
                    addressBook.BytesAddressBookItem = msgBytes;
                    syncAddressBook.data = addressBook;
                    synchronisation = syncAddressBook;
                    MTpacket.body.datablocks.Add(synchronisation);
                    //to complete
                    break;
                  case SynchronisationDataType.EmergencyCallRecipient:
                    DataBlock_SynchronisationEmergencyCallRecipient syncEmergCallRec = new DataBlock_SynchronisationEmergencyCallRecipient();
                    syncEmergCallRec.blockType = (int)ICDBlockType.Synchronisation;
                    syncEmergCallRec.BlockType = ICDBlockType.Synchronisation;
                    msg = "emergencycallrecipient";
                    syncEmergCallRec.BlockLengthBytes = (uint)(msg.Length + 2);
                    syncEmergCallRec.dataType = (int)SynchronisationDataType.EmergencyCallRecipient;
                    syncEmergCallRec.DataType = SynchronisationDataType.EmergencyCallRecipient;
                    msgBytes = GetBytes(msg);
                    msgBytes = Encoding.Convert(unicode, utf8, msgBytes);
                    DataBlock_EmergencyCallRecipient emerCallRec = new DataBlock_EmergencyCallRecipient();
                    emerCallRec.EmergencyCallRecipient = msgBytes;
                    syncEmergCallRec.data = emerCallRec;
                    synchronisation = syncEmergCallRec;
                    MTpacket.body.datablocks.Add(synchronisation);
                    //to complete
                    break;
                  case SynchronisationDataType.EmergencyDestination:
                    DataBlock_SynchronisationEmergencyDestination syncEmergDest = new DataBlock_SynchronisationEmergencyDestination();
                    syncEmergDest.blockType = (int)ICDBlockType.Synchronisation;
                    syncEmergDest.BlockType = ICDBlockType.Synchronisation;
                    syncEmergDest.dataType = (int)SynchronisationDataType.EmergencyDestination;
                    syncEmergDest.DataType = SynchronisationDataType.EmergencyDestination;
                    //to complete
                    break;
                  case SynchronisationDataType.GPSFrequencyRate:
                    DataBlock_SynchronisationReportingFrequencyRate repFreqRate = new DataBlock_SynchronisationReportingFrequencyRate();
                    //to complete
                    break;
                  case SynchronisationDataType.ProtocolType:
                    DataBlock_SynchronisationProtocolType protocolType = new DataBlock_SynchronisationProtocolType();
                    //to complete
                    break;
                }
                msgs.Add(MTpacket.ToBytes());
                break;
            }//termina switch principal
              }//termina while
              if (msgs.Count > 0)
              {
            return true;
              }
              else
              {
            return false;
              }
            }//termina if
            else
            {
              return false;
            }
            #endregion
              }
              catch (Exception ex)
              {
            log.writeToLogFile(LogType.LOG_NOTICE, "ConnectToDatabase", "Hubo un error: {0}, en la consulta: {1} ", ex.Message, sql);
            return false;
              }
        }