Inheritance: MonoBehaviour
Example #1
0
        public void InitializeMoves()
        {
            GARCMoves = GetGARCData("move");
            switch (Generation)
            {
            case 6:
                if (XY)
                {
                    Moves = GARCMoves.Files.Select(file => new Move6(file)).ToArray();
                }
                if (ORAS)
                {
                    Moves = Mini.UnpackMini(GARCMoves.getFile(0), "WD").Select(file => new Move6(file)).ToArray();
                }
                break;

            case 7:
                Moves = Mini.UnpackMini(GARCMoves.getFile(0), "WD").Select(file => new Move7(file)).ToArray();
                break;
            }
        }
        protected void del_Click(object sender, EventArgs e)
        {
            Mini   mini     = new Mini();
            string mininame = Request.QueryString["Mini"];
            var    filepath = MapPath("~/App_Data/Assign04.json");

            if (File.Exists(filepath))
            {
                var lists = JsonConvert.DeserializeObject <List <Mini> >(File.ReadAllText(filepath));
                foreach (var mdl in lists)
                {
                    if (mdl.MiniName == mininame)
                    {
                        mini = mdl;
                    }
                }
                lists.Remove(mini);
                File.WriteAllText(filepath, JsonConvert.SerializeObject(lists));
                Response.Redirect("~/Default.aspx");
            }
        }
Example #3
0
        /// <summary>
        /// Build the C# result that can be used to generate the Json result for GetSeries.
        /// </summary>
        public IEnumerable <ValueSerie> RetrieveSerieValuesForAccount(Mini mini, DateTime inFromUtc, DateTime inToUtc, SeriesResolution inResolution)
        {
            var parameters = new RetrieveSeriesParameters
            {
                Mini       = mini,
                FromUtc    = inFromUtc,
                ToUtc      = inToUtc,
                Resolution = inResolution
            };
            List <ValueSerie> resultSeries = RetrieveQboxSeries(parameters);

            // If there is generation, it can be that there are odd negative consumption numbers, these will be set to 0.
            if (resultSeries.Any(s => s.EnergyType == DeviceEnergyType.Generation) && resultSeries.Any(s => s.EnergyType == DeviceEnergyType.Consumption))
            {
                foreach (var datum in resultSeries.First(s => s.EnergyType == DeviceEnergyType.Consumption).Data.Where(d => d.Value.HasValue && d.Value < 0))
                {
                    datum.Value = 0;
                }
            }
            return(resultSeries);
        }
Example #4
0
        /// <summary>
        /// Retrieve live energy data for an account.
        /// </summary>
        /// <remarks>
        /// Does not check read permissions.
        /// </remarks>
        /// <returns>
        /// Live data for each active device of the account.
        /// </returns>
        public IList <LiveDataForDevice> Retrieve(Mini mini, DateTime nowUtc)
        {
            var toUtc   = nowUtc.Truncate(TimeSpan.FromMinutes(1));
            var fromUtc = toUtc.AddMinutes(-5);

            var liveData = new List <LiveDataForDevice>();
            IEnumerable <ValueSerie> seriesList = _seriesRetriever.RetrieveSerieValuesForAccount(mini, fromUtc, toUtc, SeriesResolution.OneMinute);

            foreach (var series in seriesList)
            {
                decimal?power = Series2Power(series.Data);
                liveData.Add(new LiveDataForDevice
                {
                    EnergyType = series.EnergyType,
                    Name       = series.Name,
                    Power      = power
                });
            }

            return(liveData);
        }
Example #5
0
        public void Handle_DataMessage()
        {
            const string message =
                @"FAFB070DABB7440780/KFM5KAIFA-METER 1-3:0.2.8(40) 0-0:1.0.0(000102045905W) 
0 - 0:96.1.1(4530303033303030303030303032343133)
1 - 0:1.8.1(000181.011 * kWh)
1 - 0:1.8.2(000182.044 * kWh)
1 - 0:2.8.1(000281.099 * kWh)
1 - 0:2.8.2(000282.077 * kWh)
0 - 0:96.14.0(0001) 1 - 0:1.7.0(00.034 * kW)
1 - 0:2.7.0(00.000 * kW) 0 - 0:17.0.0(999.9 * kW) 0 - 0:96.3.10(1) 0 - 0:96.7.21(00073)
0 - 0:96.7.9(00020) 1 - 0:99.97.0(3)(0 - 0:96.7.19)(000124235657W)(0000003149 * s)(000124225935W)(0000000289 * s)(000101000001W)(2147483647 * s)
1 - 0:32.32.0(00005) 1 - 0:52.32.0(00006) 1 - 0:72.32.0(00001) 1 - 0:32.36.0(00000)
1 - 0:52.36.0(00000) 1 - 0:72.36.0(00000) 0 - 0:96.13.1() 0 - 0:96.13.0() 1 - 0:31.7.0(000 * A)
1 - 0:51.7.0(000 * A) 1 - 0:71.7.0(000 * A) 1 - 0:21.7.0(00.034 * kW) 1 - 0:22.7.0(00.000 * kW) 1 - 0:41.7.0(00.000 * kW)
1 - 0:42.7.0(00.000 * kW) 1 - 0:61.7.0(00.000 * kW) 1 - 0:62.7.0(00.000 * kW) 0 - 1:24.1.0(003)
0 - 1:96.1.0(4730303131303033303832373133363133)
0 - 1:24.2.1(000102043601W)(72869.839 * m3) 0 - 1:24.4.0(1)!583C";

            var mini = new Mini();
            var ctx  = new QboxDataDumpContext(message, 16, "localhost", "::1", mini);

            var parserFactoryMock = new Mock <IParserFactory>();
            var protocolReader    = new ProtocolReader(_protocolReaderLoggerMock.Object, message.AsMemory());

            var protocolReaderFactoryMock = new Mock <IProtocolReaderFactory>();

            protocolReaderFactoryMock.Setup(pr => pr.Create(It.IsAny <ReadOnlyMemory <char> >())).Returns(protocolReader);

            var smartMeterCounterParser = new SmartMeterCounterParser(_smartMeterLoggerMock.Object, _validators);

            parserFactoryMock.Setup(pf => pf.GetParser(It.IsAny <string>())).Returns(new MiniR21(_miniLoggerMock.Object, protocolReaderFactoryMock.Object, smartMeterCounterParser));

            var sut = new MiniDataHandler(ctx, _qboxMessagesLoggerMock.Object, parserFactoryMock.Object, _dateMock.Object);

            var result       = sut.Handle();
            var resultAsText = result.Trim('\x02', '\x03');

            resultAsText.Should().Be("FB18D6728000");
        }
Example #6
0
        public void TestValidDuo()
        {
            // Arrange
            _sut.WithType(QboxType.Duo)
            .WithSerial("00-00-000-001")
            .WithCounter(181, CounterType.Primary, Core.Dto.DeviceEnergyType.NetLow)
            .WithCounter(182, CounterType.Primary, Core.Dto.DeviceEnergyType.NetHigh)
            .WithCounter(281, CounterType.Primary, Core.Dto.DeviceEnergyType.NetLow)
            .WithCounter(282, CounterType.Primary, Core.Dto.DeviceEnergyType.NetHigh);

            // Act
            Mini mini = _sut.Build();

            // Assert
            Assert.That(mini.SerialNumber, Is.EqualTo("00-00-000-001"));
            Assert.That(mini.MeterType, Is.EqualTo(DeviceMeterType.NO_Meter));
            Assert.That(mini.SecondaryMeterType, Is.EqualTo(DeviceMeterType.NO_Meter));
            Assert.That(mini.Counters.Count, Is.EqualTo(4));
            Assert.That(mini.Clients.Count, Is.EqualTo(1));
            Assert.That(mini.Clients.First().MeterType, Is.EqualTo(DeviceMeterType.Smart_Meter_EG));
            Assert.That(mini.Clients.First().SecondaryMeterType, Is.EqualTo(DeviceMeterType.SO_Pulse));
        }
        public async Task <MiniTag> AddMiniTag(Mini mini, Tag tag, IdentityUser user)
        {
            MiniTag newMiniTag = new MiniTag()
            {
                Mini             = mini,
                MiniID           = mini.ID,
                Tag              = tag,
                TagID            = tag.ID,
                Tagger           = user,
                Status           = Status.Pending,
                CreatedTime      = DateTime.Now,
                LastModifiedTime = DateTime.Now
            };

            if (!mini.MiniTags.Where(mt => mt.Tag.TagName == tag.TagName).Any())
            {
                tag.MiniTags.Add(newMiniTag);
                mini.MiniTags.Add(newMiniTag);
                _context.MiniTag.Add(newMiniTag);
            }
            else
            {
                newMiniTag = mini.MiniTags.Where(mt => mt.Tag.TagName == tag.TagName).First();

                if (newMiniTag.Status == Status.Pending || newMiniTag.Status == Status.Approved)
                {
                    return(newMiniTag);
                }
                newMiniTag.Status = Status.Pending;
            }

            foreach (Tag pairedTag in FindPairedTags(tag))
            {
                AddMiniTag(mini, pairedTag, user);
            }

            return(newMiniTag);
        }
Example #8
0
        public async Task <Mini> ParseFromUrl(Uri url)
        {
            HtmlWeb      web     = new HtmlWeb();
            HtmlDocument htmlDoc = await web.LoadFromWebAsync(url, null, null);

            // atelierstoria.com only has minis created by atelierstoria
            Creator creator = new Creator
            {
                Name = "atelierstoria"
            };
            AtelierStoriaSource source = new AtelierStoriaSource(creator);

            creator.Sites.Add(source);

            // URLs come in the form 'https://atelierstoria.com/collections/collection/mini?variant=variantId'
            // Some minis have variants, in which case they have a single query parameter named variant.
            var variantId = url.Query.Split("=").Last();

            // If the variant is not specified in the URL query, the default variant will be used when avaiable.
            // If the default variant doesn't exist, variantId will still be an empty string.
            if (variantId == "")
            {
                variantId = GetValueFromMeta(htmlDoc, "product:defaultvariant", "");
            }

            Mini mini = new Mini()
            {
                Creator   = creator,
                Name      = GetValueFromMeta(htmlDoc, "product:title:", variantId),
                Thumbnail = GetValueFromMeta(htmlDoc, "product:image:", variantId),
                Cost      = GetCost(htmlDoc, variantId),
                Link      = url.ToString(),
            };

            mini.Sources.Add(new MiniSourceSite(mini, source, url));

            return(mini);
        }
Example #9
0
        public void save()
        {
            Mini mini = new Mini();

            mini.MiniName       = MiniNameTextBox.Text;
            mini.faction        = FactionTextBox.Text;
            mini.rank           = Convert.ToInt32(RankTextBox.Text);
            mini._base          = Convert.ToInt32(BaseTextBox.Text);
            mini.size           = Convert.ToInt32(SizeTextBox.Text);
            mini.deploymentZone = DeploymentZoneTextBox.Text;
            mini.mobility       = Convert.ToInt32(MobilityTextBox.Text);
            mini.willpower      = Convert.ToInt32(WillpowerTextBox.Text);
            mini.resiliance     = Convert.ToInt32(ResilianceTextBox.Text);
            var    filepath = MapPath("~/App_Data/Assign04.json");
            string strng    = File.ReadAllText(filepath);

            if (File.Exists(filepath))
            {
                var writedata = JsonConvert.DeserializeObject <List <Mini> >(strng);
                writedata.Add(mini);
                File.WriteAllText(filepath, JsonConvert.SerializeObject(writedata));
            }
        }
Example #10
0
        private Mini CreateMini(string qboxSerial)
        {
            var mini = new Mini()
            {
                SerialNumber       = qboxSerial,
                Precision          = Precision.mWh,
                AutoAnswer         = true,
                MeterType          = _qboxType == QboxType.Mono ? DeviceMeterType.Smart_Meter_EG : DeviceMeterType.NO_Meter,
                SecondaryMeterType = _qboxType == QboxType.Mono ? DeviceMeterType.SO_Pulse : DeviceMeterType.NO_Meter,
            };

            if (_qboxType == QboxType.Duo)
            {
                mini.Clients.Add(new ClientQbox
                {
                    ClientId           = 0,
                    MeterType          = DeviceMeterType.Smart_Meter_EG,
                    SecondaryMeterType = DeviceMeterType.SO_Pulse
                });
            }

            return(mini);
        }
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            _telemetry.TrackEvent("CreatedMini", new Dictionary <string, string> {
                { "URL", URL.ToString() }
            });

            IdentityUser user = await _userManager.GetUserAsync(User);

            Mini mini = await _mediator.Send(new MiniSubmissionRequest(URL, user, false));

            //TODO: Display an error....
            if (mini is null)
            {
                return(Page());
            }

            return(RedirectToPage("./Edit", new { id = mini.ID, showHelp = "create" }));
        }
Example #12
0
        [InlineData("2F100718D9A3C41E00", "1018D6728000")] // Qbox van R. versie 47 nieuw
        public void Handle_NoMeterMessage(string message, string response)
        {
            var mini = new Mini();
            var ctx  = new QboxDataDumpContext(message, 16, "localhost", "::1", mini);

            var parserFactoryMock = new Mock <IParserFactory>();
            var protocolReader    = new ProtocolReader(_protocolReaderLoggerMock.Object, message.AsMemory());

            var protocolReaderFactoryMock = new Mock <IProtocolReaderFactory>();

            protocolReaderFactoryMock.Setup(pr => pr.Create(It.IsAny <ReadOnlyMemory <char> >())).Returns(protocolReader);

            var smartMeterCounterParser = new SmartMeterCounterParser(_smartMeterLoggerMock.Object, _validators);

            parserFactoryMock.Setup(pf => pf.GetParser(It.IsAny <string>())).Returns(new MiniR21(_miniLoggerMock.Object, protocolReaderFactoryMock.Object, smartMeterCounterParser));

            var sut = new MiniDataHandler(ctx, _qboxMessagesLoggerMock.Object, parserFactoryMock.Object, _dateMock.Object);

            var result       = sut.Handle();
            var resultAsText = result.Trim('\x02', '\x03');

            resultAsText.Should().Be(response);
        }
Example #13
0
        public static void _miniUpdate(Mini mini)
        {
            if (Camouflager.camouflageTimer > 0f)
            {
                return;
            }

            float  growingProgress = mini.growingProgress();
            float  scale           = growingProgress * 0.35f + 0.35f;
            string suffix          = "";

            if (growingProgress != 1f)
            {
                suffix = " <color=#FAD934FF>(" + Mathf.FloorToInt(growingProgress * 18) + ")</color>";
            }

            if (!Helpers.hidePlayerName(mini.player))
            {
                mini.player.nameText.text += suffix;
            }

            if (MeetingHud.Instance != null)
            {
                foreach (PlayerVoteArea player in MeetingHud.Instance.playerStates)
                {
                    if (player.NameText != null && mini.player.PlayerId == player.TargetPlayerId)
                    {
                        player.NameText.text += suffix;
                    }
                }
            }

            if (Morphling.morphling != null && Morphling.morphTarget == mini.player && Morphling.morphTimer > 0f && !Helpers.hidePlayerName(Morphling.morphling))
            {
                Morphling.morphling.nameText.text += suffix;
            }
        }
Example #14
0
        public static Area7[] GetArray(lzGARCFile ed, ZoneData7[] zd)
        {
            int fileCount = ed.FileCount;
            var numAreas  = fileCount / 11;
            var areas     = new Area7[numAreas];

            for (int i = 0; i < numAreas; i++)
            {
                areas[i] = new Area7
                {
                    FileNumber = 9 + (11 * i),
                    Zones      = zd.Where(z => z.AreaIndex == i).ToArray()
                };
                var md = ed[areas[i].FileNumber];
                if (md.Length <= 0)
                {
                    areas[i].HasTables = false;
                    continue;
                }

                byte[][] Tables = Mini.UnpackMini(md, PackIdentifier);
                areas[i].HasTables = Tables.Any(t => t.Length > 0);
                if (!areas[i].HasTables)
                {
                    continue;
                }

                foreach (var Table in Tables)
                {
                    var DayTable   = Table.Skip(4).Take(0x164).ToArray();
                    var NightTable = Table.Skip(0x168).ToArray();
                    areas[i].Tables.Add(new EncounterTable(DayTable));
                    areas[i].Tables.Add(new EncounterTable(NightTable));
                }
            }
            return(areas);
        }
Example #15
0
        private void GetEntry()
        {
            if (entry < 0)
            {
                return;
            }
            byte[] raw = File.ReadAllBytes(filepaths[entry]);
            locationData = Mini.UnpackMini(raw, "ZO");
            if (locationData == null)
            {
                return;
            }

            // Read master ZD table
            byte[] zd = masterZoneData.Skip(ZoneData.Size * entry).Take(ZoneData.Size).ToArray();
            RTB_ZDMaster.Lines = Scripts.getHexLines(zd, 0x10);

            // Load from location Data.
            CurrentZone = new Zone(locationData);
            // File 0 - ZoneData
            RTB_ZD.Lines = Scripts.getHexLines(locationData[0], 0x10);
            GetZoneData();

            // File 1 - Overworld Setup & Script
            RTB_OWSC.Lines = Scripts.getHexLines(locationData[1], 0x10);
            GetOWSData();

            // File 2 - Map Script
            RTB_MapSC.Lines = Scripts.getHexLines(locationData[2], 0x10);
            GetScriptData();

            // File 3 - Encounters
            RTB_Encounter.Lines = Scripts.getHexLines(locationData[3], 0x10);

            // File 4 - ?? (ORAS Only?)
            RTB_File5.Lines = Scripts.getHexLines(locationData.Length <= 4 ? null : locationData[4], 0x10);
        }
        public async Task <Mini> ParseFromUrl(Uri url)
        {
            HtmlWeb      web     = new HtmlWeb();
            HtmlDocument htmlDoc = await web.LoadFromWebAsync(url, null, null);

            HtmlNode nameNode  = htmlDoc.DocumentNode.SelectNodes("//meta[@property=\"og:title\"]").First();
            HtmlNode imageNode = htmlDoc.DocumentNode.SelectNodes("//meta[@property=\"og:image\"]").First();
            HtmlNode urlNode   = htmlDoc.DocumentNode.SelectNodes("//meta[@property=\"og:url\"]").First();
            HtmlNode costNode  = htmlDoc.DocumentNode.SelectNodes("//meta[@property=\"product:price:amount\"]").First();

            Uri link = new Uri(urlNode.GetAttributeValue("content", url.ToString()));

            string creatorName = link.Host.Split('.').First().Split('/').Last();

            Creator creator = new Creator
            {
                Name = creatorName
            };
            GumroadSource source = new GumroadSource(creator, creatorName);

            creator.Sites.Add(source);

            Mini mini = new Mini()
            {
                Creator   = creator,
                Name      = System.Web.HttpUtility.HtmlDecode(nameNode.GetAttributeValue("content", null)),
                Thumbnail = imageNode.GetAttributeValue("content", null),
                Link      = "https://gumroad.com" + link.AbsolutePath
            };

            mini.Cost = Convert.ToInt32(Math.Round(Convert.ToDouble(costNode.GetAttributeValue("content", "0"))));
            ;
            mini.Sources.Add(new MiniSourceSite(mini, source, url));

            return(mini);
        }
Example #17
0
        public void save()
        {
            Mini mini = new Mini();

            mini.MiniName       = nametxt.Text;
            mini.faction        = facttxt.Text;
            mini.willpower      = Convert.ToInt32(willtxt.Text);
            mini.resiliance     = Convert.ToInt32(restxt.Text);
            mini.wounds         = Convert.ToInt32(woundtxt.Text);
            mini.mobility       = Convert.ToInt32(mobtxt.Text);
            mini.rank           = Convert.ToInt32(ranktxt.Text);
            mini.deploymentZone = deptxt.Text;
            mini._base          = Convert.ToInt32(basetxt.Text);
            mini.size           = Convert.ToInt32(sizetxt.Text);
            var    filepath = MapPath("~/Assign04.json");
            string strng    = File.ReadAllText(filepath);

            if (File.Exists(filepath))
            {
                var writedata = JsonConvert.DeserializeObject <List <Mini> >(strng);
                writedata.Add(mini);
                File.WriteAllText(filepath, JsonConvert.SerializeObject(writedata));
            }
        }
Example #18
0
        public void SerializationJsn()
        {
            //Storing the txtboxes values to mini here
            // this method was easir for my undrestanding to do the serialization and
            //saving it to jason file.
            Mini mini = new Mini();

            mini.name           = txtbxName.Text;
            mini.faction        = txtbxFaction.Text;
            mini.size           = Convert.ToInt32(txtbxSize.Text);
            mini.rank           = Convert.ToInt32(txtbxRank.Text);
            mini.deploymentZone = txtbxDeployment.Text;
            mini._base          = Convert.ToInt32(txtbxBase.Text);

            filePath = System.Web.Hosting.HostingEnvironment.MapPath("~/Asset/Assign04.json");
            if (File.Exists(filePath))
            {
                var converToJsonRecord = JsonConvert.DeserializeObject <List <Mini> >(File.ReadAllText(filePath));
                converToJsonRecord.Add(mini);
                File.WriteAllText(filePath, JsonConvert.SerializeObject(converToJsonRecord));
                this.sentEmails();
                Response.Redirect("~/home.aspx");
            }
        }
Example #19
0
        private void SetEntry()
        {
            if (entry < 0)
            {
                return;
            }
            if (debugToolDumping)
            {
                return;
            }

            // Set the data back into the class object
            // Currently only the first two files.
            SetZoneData(); // File 0
            SetOWSData();
            // setMSData();
            // setEncounterData();
            // if (Main.Config.ORAS)
            //     setUnknown();

            // Reassemble files
            byte[][] data = CurrentZone.Write();

            // Debug Check (can stay, why not.)
            if (!locationData.Where((t, i) => !data[i].SequenceEqual(t)).Any())
            {
                return;
            }

            // Util.Alert("Zone has been edited!");
            System.Media.SystemSounds.Asterisk.Play();

            // Package the files into the permanent package file.
            byte[] raw = Mini.PackMini(data, "ZO");
            File.WriteAllBytes(filepaths[entry], raw);
        }
Example #20
0
 /// <summary>
 /// Is inMini a Ferraris meter?
 /// </summary>
 private bool IsFerrarisMeter(Mini inMini)
 {
     return(inMini.IsMeterTypePresent(DeviceMeterType.Ferraris_Black_Toothed));
 }
Example #21
0
        private void SaveARC(string path)
        {
            if (!Directory.Exists(path))
            {
                WinFormsUtil.Error("Input path is not a Folder", path); return;
            }
            string folderName = Path.GetFileName(path);
            string parentName = Directory.GetParent(path).FullName;
            int    type       = CB_Repack.SelectedIndex;

            switch (type)
            {
            case 0:     // AutoDetect
            {
                if (!folderName.Contains("_"))
                {
                    WinFormsUtil.Alert("Unable to autodetect pack type."); return;
                }

                if (folderName.Contains("_g"))
                {
                    goto case 1;
                }
                if (folderName.Contains("_d"))
                {
                    goto case 2;
                }
                // else
                goto case 3;
            }

            case 1:     // GARC Pack
            {
                if (threads > 0)
                {
                    WinFormsUtil.Alert("Please wait for all operations to finish first."); return;
                }
                DialogResult dr = WinFormsUtil.Prompt(MessageBoxButtons.YesNoCancel, "Format Selection:",
                                                      "Yes: Sun/Moon (Version 6)\nNo: XY/ORAS (Version 4)");
                if (dr == DialogResult.Cancel)
                {
                    return;
                }

                var version = dr == DialogResult.Yes ? GARC.VER_6 : GARC.VER_4;
                int padding = (int)NUD_Padding.Value;
                if (version == GARC.VER_4)
                {
                    padding = 4;
                }

                string outfolder = Directory.GetParent(path).FullName;
                new Thread(() =>
                    {
                        bool r = GarcUtil.PackGARC(path, Path.Combine(outfolder, folderName + ".garc"), version, padding, pBar1);
                        if (!r)
                        {
                            WinFormsUtil.Alert("Packing failed."); return;
                        }
                        // Delete path after repacking
                        if (CHK_Delete.Checked && Directory.Exists(path))
                        {
                            Directory.Delete(path, true);
                        }

                        System.Media.SystemSounds.Asterisk.Play();
                    }).Start();
                return;
            }

            case 2:     // DARC Pack (from existing if exists)
            {
                string oldFile = path.Replace("_d", "");
                if (File.Exists(Path.Combine(parentName, oldFile)))
                {
                    oldFile = Path.Combine(parentName, oldFile);
                }
                else if (File.Exists(Path.Combine(parentName, oldFile + ".bin")))
                {
                    oldFile = Path.Combine(parentName, oldFile + ".bin");
                }
                else if (File.Exists(Path.Combine(parentName, oldFile + ".darc")))
                {
                    oldFile = Path.Combine(parentName, oldFile + ".darc");
                }
                else
                {
                    oldFile = null;
                }

                bool r = Core.CTR.DARC.Files2darc(path, false, oldFile);
                if (!r)
                {
                    WinFormsUtil.Alert("Packing failed.");
                }
                break;
            }

            case 3:     // Mini Pack
            {
                // Get Folder Name
                string fileName = Path.GetFileName(path);
                if (fileName.Length < 3)
                {
                    WinFormsUtil.Error("Mini Folder name not valid:", path); return;
                }

                int    index   = fileName.LastIndexOf('_');
                string fileNum = fileName.Substring(0, index);
                string fileExt = fileName.Substring(index + 1);

                // Find old file for reference...
                string file;
                if (File.Exists(Path.Combine(parentName, fileNum + ".bin")))
                {
                    file = Path.Combine(parentName, fileNum + ".bin");
                }
                else if (File.Exists(Path.Combine(parentName, fileNum + "." + fileExt)))
                {
                    file = Path.Combine(parentName, fileNum + "." + fileExt);
                }
                else
                {
                    file = null;
                }

                byte[] oldData = file != null?File.ReadAllBytes(file) : null;

                bool r = Mini.PackMini2(path, fileExt, Path.Combine(parentName, fileNum + "." + fileExt));
                if (!r)
                {
                    WinFormsUtil.Alert("Packing failed.");
                    break;
                }

                // Check to see if the header size is different...
                if (oldData == null)     // No data to compare to.
                {
                    break;
                }

                byte[] newData = File.ReadAllBytes(Path.Combine(parentName, fileNum + "." + fileExt));
                if (newData[2] == oldData[2])
                {
                    int newPtr = BitConverter.ToInt32(newData, 4);
                    int oldPtr = BitConverter.ToInt32(oldData, 4);
                    if (newPtr != oldPtr)     // Header size is different. Prompt repointing.
                    {
                        if (DialogResult.Yes != WinFormsUtil.Prompt(MessageBoxButtons.YesNo, "Header size of existing file is nonstandard.", "Adjust newly packed file to have the same header size as old file? Data pointers will be updated accordingly."))
                        {
                            break;
                        }

                        // Fix pointers
                        byte[] update = Mini.AdjustMiniHeader(newData, oldPtr);
                        File.WriteAllBytes(Path.Combine(parentName, fileNum + "." + fileExt), update);
                    }
                }

                break;
            }

            default:
                WinFormsUtil.Alert("Repacking not implemented." + Environment.NewLine + path);
                return;
            }
            // Delete path after repacking
            if (CHK_Delete.Checked && Directory.Exists(path))
            {
                Directory.Delete(path, true);
            }
            System.Media.SystemSounds.Asterisk.Play();
        }
Example #22
0
        internal static void OpenARC(string path, ProgressBar pBar1, bool recursing = false)
        {
            string newFolder = "";

            try
            {
                // Pre-check file length to see if it is at least valid.
                FileInfo fi = new FileInfo(path);
                if (fi.Length > (long)2 * (1 << 30))
                {
                    WinFormsUtil.Error("File is too big!"); return;
                }                                                                                      // 2 GB
                string folderPath = Path.Combine(Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(path));

                byte[] first4 = new byte[4];
                try
                {
                    using var fs = new FileStream(path, FileMode.Open);
                    using var bw = new BinaryReader(fs);
                    first4       = bw.ReadBytes(4);
                }
                catch (Exception e)
                {
                    WinFormsUtil.Error("Cannot open file!", e.ToString());
                }

                // Determine if it is a DARC or a Mini
                // Check if Mini first
                string fx = fi.Length > 10 * (1 << 20) ? null : Mini.GetIsMini(path); // no mini is above 10MB
                if (fx != null)                                                       // Is Mini Packed File
                {
                    newFolder = folderPath + "_" + fx;
                    // Fetch Mini File Contents
                    Mini.UnpackMini(path, fx, newFolder, false);
                    // Recurse throught the extracted contents if they extract successfully
                    if (Directory.Exists(newFolder))
                    {
                        foreach (string file in Directory.GetFiles(newFolder))
                        {
                            OpenARC(file, pBar1, true);
                        }
                        BatchRenameExtension(newFolder);
                    }
                }
                else if (first4.SequenceEqual(BitConverter.GetBytes(0x54594C41))) // ALYT
                {
                    if (threads > 0)
                    {
                        WinFormsUtil.Alert("Please wait for all operations to finish first."); return;
                    }
                    new Thread(() =>
                    {
                        Interlocked.Increment(ref threads);
                        var alyt = new ALYT(File.ReadAllBytes(path));
                        var sarc = new SARC(alyt.Data) // rip out sarc
                        {
                            FileName = Path.GetFileNameWithoutExtension(path) + "_sarc",
                            FilePath = Path.GetDirectoryName(path)
                        };
                        if (!sarc.Valid)
                        {
                            return;
                        }
                        var files = sarc.Dump();
                        foreach (var _ in files)
                        {
                            // openARC(file, pBar1, true);
                        }
                        Interlocked.Decrement(ref threads);
                    }).Start();
                }
                else if (first4.SequenceEqual(BitConverter.GetBytes(0x47415243))) // GARC
                {
                    if (threads > 0)
                    {
                        WinFormsUtil.Alert("Please wait for all operations to finish first."); return;
                    }
                    bool SkipDecompression = ModifierKeys == Keys.Control;
                    new Thread(() =>
                    {
                        Interlocked.Increment(ref threads);
                        bool r = GarcUtil.UnpackGARC(path, folderPath + "_g", SkipDecompression, pBar1);
                        Interlocked.Decrement(ref threads);
                        if (r)
                        {
                            BatchRenameExtension(newFolder);
                        }
                        else
                        {
                            WinFormsUtil.Alert("Unpacking failed."); return;
                        }
                        System.Media.SystemSounds.Asterisk.Play();
                    }).Start();
                }
                else if (ARC.Analyze(path).valid) // DARC
                {
                    var data = File.ReadAllBytes(path);
                    int pos  = 0;
                    while (BitConverter.ToUInt32(data, pos) != 0x63726164)
                    {
                        pos += 4;
                        if (pos >= data.Length)
                        {
                            return;
                        }
                    }
                    var darcData = data.Skip(pos).ToArray();
                    newFolder = folderPath + "_d";
                    bool r = Core.CTR.DARC.Darc2files(darcData, newFolder);
                    if (!r)
                    {
                        WinFormsUtil.Alert("Unpacking failed.");
                    }
                }
                else if (ARC.AnalyzeSARC(path).Valid)
                {
                    var sarc = ARC.AnalyzeSARC(path);
                    Console.WriteLine($"New SARC with {sarc.SFAT.EntryCount} files.");
                    foreach (var _ in sarc.Dump(path))
                    {
                    }
                }
                else if (!recursing)
                {
                    WinFormsUtil.Alert("File is not a darc or a mini packed file:" + Environment.NewLine + path);
                }
            }
            catch (Exception e)
            {
                if (!recursing)
                {
                    WinFormsUtil.Error("File error:" + Environment.NewLine + path, e.ToString());
                }
                threads = 0;
            }
        }
Example #23
0
        /// <summary>
        /// Constructs the data for the handling of a qbox data dump
        /// </summary>
        /// <param name="message">The actual message dumped by the Qbox. This is the decrypted message!</param>
        /// <param name="length">The length of the message</param>
        /// <param name="lastSeenAtUrl">The url used to dump the message</param>
        /// <param name="externalIp">The external ip from which the dump was initiated</param>
        /// <param name="mini">The mini the dump is made from</param>
        /// <param name="error">An optional error message to show if the retrieval or binding of the Mini, MiniPoco or decryption of the message was incorrect.</param>
        public QboxDataDumpContext(string message, int length, string lastSeenAtUrl, string externalIp, Mini mini, string error = null)
        {
            Guard.IsNotNullOrEmpty(lastSeenAtUrl, "last seen url is missing");
            Guard.IsNotNullOrEmpty(externalIp, "External Ip is missing");
            Guard.IsNotNullOrEmpty(message, "message is missing");

            Message = message;
            Length  = length;
            Mini    = mini;
            Error   = error;
            if (Mini != null)
            {
                Mini.QboxStatus.IpAddress[externalIp] = DateTime.Now.ToUniversalTime();
                Mini.QboxStatus.Url = lastSeenAtUrl;
            }
        }
Example #24
0
 /// <summary>
 /// Is inMini a LED meter?
 /// </summary>
 private bool IsLedMeter(Mini inMini)
 {
     return(inMini.IsMeterTypePresent(DeviceMeterType.LED_TypeI) || inMini.IsMeterTypePresent(DeviceMeterType.LED_TypeII));
 }
Example #25
0
            public override void OnFetch(Mini.Context.IComponentContext ctx)
            {
                Console.WriteLine(string.Format("DI container Fetch {0} component", ctx.Instance.GetType().Name));

            }
Example #26
0
 /// <summary>
 /// Is inMini a duo meter?
 /// </summary>
 private bool IsDuo(Mini inMini)
 {
     return(inMini.Clients.Any());
 }
Example #27
0
        private static Mini CreateMini(string qboxSerial)
        {
            // SAM: previously the Qbox metadata was read from Redis. For now we take a huge shortcut and
            // only support Qbox Duo with smart meter EG with S0.
            // This code is tied to a similar construct in Qserver (QboxDataDumpContextFactory.Mini).
            var qbox = new Qbox
            {
                SerialNumber = qboxSerial,
                Precision    = Precision.mWh,
                DataStore    = new DataStore
                {
                    Path = QboxNext.Core.Config.DataStorePath
                }
            };
            var mini = new Mini
            {
                Counters = new List <Counter>()
                {
                    new Counter
                    {
                        CounterId             = 181,
                        GroupId               = CounterSource.Client0,
                        CounterDeviceMappings = new List <CounterDeviceMapping>
                        {
                            new CounterDeviceMapping
                            {
                                Device = new Device
                                {
                                    EnergyType = DeviceEnergyType.Consumption
                                },
                                PeriodeBegin = new DateTime(2012, 1, 1),
                                PeriodeEind  = new DateTime(9999, 1, 1)
                            }
                        },
                        Qbox = qbox
                    },
                    new Counter
                    {
                        CounterId             = 182,
                        GroupId               = CounterSource.Client0,
                        CounterDeviceMappings = new List <CounterDeviceMapping>
                        {
                            new CounterDeviceMapping
                            {
                                Device = new Device
                                {
                                    EnergyType = DeviceEnergyType.Consumption
                                },
                                PeriodeBegin = new DateTime(2012, 1, 1),
                                PeriodeEind  = new DateTime(9999, 1, 1)
                            }
                        },
                        Qbox = qbox
                    },
                    new Counter
                    {
                        CounterId             = 281,
                        GroupId               = CounterSource.Client0,
                        CounterDeviceMappings = new List <CounterDeviceMapping>
                        {
                            new CounterDeviceMapping
                            {
                                Device = new Device
                                {
                                    EnergyType = DeviceEnergyType.Generation
                                },
                                PeriodeBegin = new DateTime(2012, 1, 1),
                                PeriodeEind  = new DateTime(9999, 1, 1)
                            }
                        },
                        Qbox = qbox
                    },
                    new Counter
                    {
                        CounterId             = 282,
                        GroupId               = CounterSource.Client0,
                        CounterDeviceMappings = new List <CounterDeviceMapping>
                        {
                            new CounterDeviceMapping
                            {
                                Device = new Device
                                {
                                    EnergyType = DeviceEnergyType.Generation
                                },
                                PeriodeBegin = new DateTime(2012, 1, 1),
                                PeriodeEind  = new DateTime(9999, 1, 1)
                            }
                        },
                        Qbox = qbox
                    },
                    new Counter
                    {
                        CounterId             = 2421,
                        GroupId               = CounterSource.Client0,
                        CounterDeviceMappings = new List <CounterDeviceMapping>
                        {
                            new CounterDeviceMapping
                            {
                                Device = new Device
                                {
                                    EnergyType = DeviceEnergyType.Gas
                                },
                                PeriodeBegin = new DateTime(2012, 1, 1),
                                PeriodeEind  = new DateTime(9999, 1, 1)
                            }
                        },
                        Qbox = qbox
                    },
                    new Counter
                    {
                        CounterId             = 1,
                        GroupId               = CounterSource.Client0,
                        Secondary             = true,
                        CounterDeviceMappings = new List <CounterDeviceMapping>
                        {
                            new CounterDeviceMapping
                            {
                                Device = new Device
                                {
                                    EnergyType = DeviceEnergyType.Generation
                                },
                                PeriodeBegin = new DateTime(2012, 1, 1),
                                PeriodeEind  = new DateTime(9999, 1, 1)
                            }
                        },
                        Qbox = qbox
                    }
                }
            };

            foreach (var counter in mini.Counters)
            {
                counter.ComposeStorageid();
            }

            return(mini);
        }
Example #28
0
        /// <summary>
        /// Get the auto answer commands for the host Qbox.
        /// </summary>
        private List <string> GetAutoAnswerCommandsForHost()
        {
            var commandsToCombine = new List <string>();
            var separateCommands  = new List <string>();

            // Host qbox
            switch (_mini.State)
            {
            case MiniState.HardReset:
                break;

            case MiniState.Waiting:
                // Host metertype
                commandsToCombine.Add(Mini.WriteMeterType(_mini.MeterType));

                if (_mini.SecondaryMeterType != DeviceMeterType.None)
                {
                    commandsToCombine.Add(Command.Encode((byte)DeviceSettingType.SecondaryMeterType, (byte)_mini.SecondaryMeterType));
                }

                if (_mini.MeterType != DeviceMeterType.NO_Meter)
                {
                    // Last known meter settings send to qbox
                    var meterSettings = _mini.MeterSettings;
                    // Default metersettings in case no last meter settings are found
                    if (String.IsNullOrEmpty(meterSettings))
                    {
                        meterSettings = Command.DefaultMeterSettings(_mini.MeterType, QboxClient.None);
                    }

                    // Since the meter settings may contain commands that can not be safely combined with other commands,
                    // for example set meter type to led + set led channel, we put the meter settings in separate command.
                    if (!String.IsNullOrEmpty(meterSettings))
                    {
                        separateCommands.Add(meterSettings);
                    }
                }

                foreach (var client in _mini.Clients)
                {
                    commandsToCombine.Add(Command.Encode((byte)ClientActivityRequest.RequestToRestartClientWithFactoryDefaults, client.ClientId));
                }

                break;

            case MiniState.ValidImage:
                break;

            case MiniState.InvalidImage:
                commandsToCombine.Add(Command.Encode(Command.RequestUpgradeFirmware));
                break;
            }

            var commands = new List <string>();

            if (commandsToCombine.Count > 0)
            {
                commands.Add(String.Join(String.Empty, commandsToCombine));
            }
            if (separateCommands.Count > 0)
            {
                commands.AddRange(separateCommands);
            }

            return(commands);
        }
Example #29
0
 private MiniContext CreateMiniContext(Mini mini)
 {
     return(new MiniContext(mini, new LambdaCommand((l, r) => {
         app.ShowMini(mini);
     })));
 }
Example #30
0
 public MiniContext(Mini mini, LambdaCommand showCommand)
 {
     this.Mini        = mini;
     this.ShowCommand = showCommand;
 }
Example #31
0
        static void Main(string[] args)
        {
            if (args.Length < 3)
            {
                if (args.Length == 1)
                {
                    switch (args[0])
                    {
                    case "listen":
                        Console.WriteLine("Pres any key to stop!");
                        using (MiniListener ml = new MiniListener(OnHaveFoundMini)) {
                            Console.ReadKey();
                        }
                        break;

                    default:
                        PrintHelp();
                        break;
                    }
                }
                else
                {
                    PrintHelp();
                }
            }
            else
            {
                Mini mini = new Mini(args[0]);
                switch (args[1])
                {
                case "slides":
                    string filename = args[2];
                    Pres   mp       = new Pres(filename);
                    mini.SendPresAsync(mp);
                    break;

                case "ncontrast":
                    int night_contrast = -1;
                    if (Int32.TryParse(args[2], out night_contrast))
                    {
                        if (night_contrast > 0)
                        {
                            mini.SendNightContrastAsync(night_contrast);
                        }
                    }
                    break;

                case "contrast":
                    int contrast = -1;
                    if (Int32.TryParse(args[2], out contrast))
                    {
                        if (contrast > 0)
                        {
                            mini.SendContrastAsync(contrast);
                        }
                    }
                    break;

                case "time":
                    mini.SendTimeAsync();
                    break;

                case "page":
                    int page = -1;
                    if (Int32.TryParse(args[2], out page))
                    {
                        if (page > 0)
                        {
                            mini.SendPageNrAsync(page);
                        }
                    }
                    break;

                case "standby":
                    string[] a = args[2].Split(",");
                    int      dh, dm, eh, em;
                    if (Int32.TryParse(a[0], out dh))
                    {
                        if (Int32.TryParse(a[1], out dm))
                        {
                            if (Int32.TryParse(a[2], out eh))
                            {
                                if (Int32.TryParse(a[3], out em))
                                {
                                    mini.SendStandbyTimeAsync(dh, dm, eh, em);
                                }
                            }
                        }
                    }
                    break;

                case "string":
                    mini.SendCustomStringAsync(args[2]);
                    break;

                case "message":
                    MessageRgb m = new MessageRgb(args[2], 2, 3, true);
                    mini.SendMessageAsync(m);
                    break;

                case "wificonf":
                    mini.SendWifiConfAsync(args[2]);
                    break;

                default:
                    Console.WriteLine("No such command!");
                    PrintHelp();
                    break;
                }
                mini.AwaitAllTasksFinished();
            }
        }