static void Main(string[] args) { IConfiguration config = new ConfigurationBuilder() .AddJsonFile("appsettings.json", true, true) .Build(); // NLog: setup the logger first to catch all errors NLog.LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration("nlog.config"); NLog.ILogger logger = NLog.LogManager.Configuration.LogFactory.GetLogger(""); string connection_string = config.GetConnectionString("mysql"); IBackgroundTaskQueue <EventSummary> queue = new BackgroundTaskQueue <EventSummary>(); EventHavestor eventHavestor = new EventHavestor(queue); MqttAddress queue_address = config.GetSection("MQTTBrokers").Get <MqttAddress>(); Console.CancelKeyPress += Console_CancelKeyPress; EventRecorder eventRecorder = new EventRecorder(logger, queue, connection_string); Task T = eventHavestor.ConnectionAsync(queue_address.ClientId, queue_address.BindAddress, queue_address.Port, queue_address.QosLevel, queue_address.Topic); T.Wait(); Task t1 = eventRecorder.RunAsync(cancellationTokenSource.Token); t1.Wait(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); MqttAddress data_mqtt_address = Configuration.GetSection("MQTTBrokers:DataBrokerAddress").Get <MqttAddress>(); services.AddSingleton(data_mqtt_address); services.AddHostedService <MqttSubscribeWorker>(); //var withOrigins = Configuration.GetSection("AllowedOrigins").Get<string[]>(); var withOrigins = Configuration.GetSection("AllowedOrigins").Get <string[]>(); services.AddCors(o => o.AddPolicy(CORS_POLICY, builder => { builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials() .WithMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .WithOrigins(withOrigins); })); services.AddSignalR(options => options.EnableDetailedErrors = true); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }
private async Task <IMqttClient> CreateMqttClient(MqttAddress addr) { var ClientOptions = new MqttClientOptions { ClientId = addr.ClientId, ChannelOptions = new MqttClientTcpOptions { Server = addr.BindAddress, Port = addr.Port, } }; var mqttClient = new MqttFactory().CreateMqttClient(); mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(async e => { //Console.WriteLine("### DISCONNECTED FROM SERVER ###"); await Task.Delay(TimeSpan.FromSeconds(1)); try { await mqttClient.ConnectAsync(ClientOptions); } catch { Console.WriteLine("### RECONNECTING FAILED ###"); } }); bool IsSuccess = false; for (int i = 0; i < 3; i++) { try { await mqttClient.ConnectAsync(ClientOptions); IsSuccess = true; break; } catch (Exception ex) { logger.LogError(ex, $"#### MQTT BROKER CONNECTING FAILED ###"); Thread.Sleep(TimeSpan.FromSeconds(30)); continue; } } if (IsSuccess == false) { logger.LogError("#### 브로커 접속에 실패했습니다. 다시 실행해주세요. ####"); return(null); } return(mqttClient); }
static void Main(string[] args) { long unix = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); DateTime dt = new DateTime(1970, 1, 1).AddSeconds(unix); DateTime newdt = dt.ToLocalTime(); Console.WriteLine("Hello World!"); MqttAddress address = new MqttAddress(); address.BindAddress = "www.peiu.co.kr"; address.Port = 2084; address.QosLevel = 2; string peiu_event_topic = $"hubbub/{6}/Event"; address.Topic = peiu_event_topic; using (EventPusher pusher = new EventPusher(address, true)) { for (int i = 0; i < 8; i++) { double pow = Math.Pow(2, i); pusher.AddEvent("PCS_FAULT1", (ushort)(100 + i), (ushort)pow); } while (true) { Console.Write("Input Value: "); string str = Console.ReadLine(); if (str.ToUpper() == "QUIT") { break; } ushort iValue; if (ushort.TryParse(str, out iValue)) { pusher.BeginProcessing(); EventSummary summary = null; bool isEvent = pusher.ProcessingEvent(6, "Jeju1", "PCS_FAULT1", iValue, ref summary); if (isEvent) { pusher.EventPushing(summary); Console.WriteLine(summary); } pusher.EndProcessing(); } } } }
public EventPusher(MqttAddress addr, bool Initialize = false) : base(addr) { _initialize = Initialize; lmdb_env = new LightningDB.LightningEnvironment("./Data"); lmdb_env.MaxDatabases = 2; lmdb_env.Open(); if (Initialize) { lmdb_env.Flush(true); } //db = lmdb_env.OpenDatabase("db_event", new DatabaseConfig(DbFlags.Create | DbFlags.IntegerKey)); }
public MqttSubscribeWorker(ILogger <MqttSubscribeWorker> _logger, MqttAddress _address, IRedisConnectionFactory _redis) { logger = _logger; mqttAddress = _address; db = _redis.Connection().GetDatabase(); }
public MqttSubscribeWorker(ILogger <MqttSubscribeWorker> _logger, MqttAddress _address, IHubContext <MeasurementHub, IClientMeasurementContract> _hubContext) { logger = _logger; mqttAddress = _address; hubContext = _hubContext; }
public MqttClientProxy(IMqttClient client, MqttAddress options) { MqttClient = client; Options = options; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //MongoDB.Driver.MongoClient client = new MongoDB.Driver.MongoClient(Configuration.GetConnectionString("mongodb")); //services.AddDbContext<AccountRecordContext>( // options => options.UseMySql(Configuration.GetConnectionString("mysqldb")) // ); services.AddDbContext <AccountDataContext>( options => options.UseMySql(Configuration.GetConnectionString("peiu_account_connnectionstring"))); var EmailSettings = Configuration.GetSection("EmailSettings:SenderName"); services.Configure <EmailSettings>(Configuration.GetSection("EmailSettings")); services.AddSingleton <IEmailSender, EmailSender>(); services.AddSingleton <IHTMLGenerator, HTMLGenerator>(); //services.AddIdentity<UserAccount>() services.AddIdentity <UserAccount, Role>(options => options.ClaimsIdentity.UserIdClaimType = "Id") .AddEntityFrameworkStores <AccountDataContext>() .AddErrorDescriber <Localization.LocalizedIdentityErrorDescriber>() .AddDefaultTokenProviders(); //add the following line of code services.AddScoped <IUserClaimsPrincipalFactory <UserAccount>, ClaimsPrincipalFactory>(); //ServiceDescriptor sd = services.FirstOrDefault(x => x.ServiceType == typeof(IdentityErrorDescriber) && x.ImplementationType == typeof(Localization.LocalizedIdentityErrorDescriber)); //sd. services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = UserClaimTypes.Issuer, ValidAudience = "https://www.peiu.co.kr", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JasonWebTokenManager.Secret)) }; options.ClaimsIssuer = UserClaimTypes.Issuer; }); //options.Configuration. //.AddCookie(); services.AddPortableObjectLocalization(options => options.ResourcesPath = "Localization"); services.AddSingleton <PeiuGridDataContext>(); ConfigureIdentity(services); ConfigureAuthrozation(services); services.AddCors(); var map_reduces = Configuration.GetSection("MongoMapReduces").Get <IEnumerable <MongoMapReduceConfig> >(); var redisConfiguration = Configuration.GetSection("redis").Get <RedisConfiguration>(); services.AddSingleton(redisConfiguration); services.AddSingleton <IRedisConnectionFactory, RedisConnectionFactory>(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info { Title = "My API", Version = "v1" }); }); MqttAddress data_mqtt_address = Configuration.GetSection("MQTTBrokers:DataBrokerAddress").Get <MqttAddress>(); services.AddSingleton(data_mqtt_address); services.AddHostedService <MqttSubscribeWorker>(); ReservedRegisterNotifyPublisher reservedRegisterNotifyPublisher = new ReservedRegisterNotifyPublisher(); reservedRegisterNotifyPublisher.Initialize(); services.AddSingleton(reservedRegisterNotifyPublisher); services.AddSingleton <Microsoft.Extensions.Hosting.IHostedService, CollectingCurrentWeatherService>(); //services.AddSingleton(client); //IServiceCollection cols = services.AddSingleton<IBackgroundMongoTaskQueue, MongoBackgroundTaskQueue>(); //services.AddSingleton<MQTTDaegunSubscribe>(); //services.AddCors(options => //{ // options.AddDefaultPolicy( // builder => // { // builder.WithOrigins("http://118.216.255.118:3011") // .AllowAnyHeader() // .AllowAnyMethod(); // }); // options.AddPolicy("PeiuPolicy", // builder => // { // builder.AllowAnyOrigin() // .AllowAnyMethod() // .AllowAnyHeader(); // //.AllowCredentials(); // }); //}); //services.Configure<MvcOptions>(options => //{ // options.Filters.Add(new RequireHttpsAttribute()); //}); //services.AddTransient<IEmailSender, EmailSender>(); services.AddPortableObjectLocalization(); services.AddSingleton <IClaimServiceFactory, ClaimServiceFactory>(); services.AddMvc() .AddViewLocalization(Microsoft.AspNetCore.Mvc.Razor.LanguageViewLocationExpanderFormat.Suffix) .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }