1 //
2 // Copyright (c) 2010-2019 Antmicro
3 //
4 // This file is licensed under the MIT License.
5 // Full license text is available in 'licenses/MIT.txt'.
6 //
7 using System;
8 using System.Collections.Generic;
9 using Antmicro.Renode.Logging;
10 using Antmicro.Renode.Peripherals;
11 
12 namespace Antmicro.Renode.Utilities
13 {
14     public class BitPatternDetector
15     {
BitPatternDetector(int width, IPeripheral loggingParent = null)16         public BitPatternDetector(int width, IPeripheral loggingParent = null) : this(new bool[width], loggingParent)
17         {
18         }
19 
BitPatternDetector(bool[] resetValue, IPeripheral loggingParent = null)20         public BitPatternDetector(bool[] resetValue, IPeripheral loggingParent = null)
21         {
22             this.loggingParent = loggingParent;
23 
24             this.resetValue = resetValue;
25             this.previousState = new bool[resetValue.Length];
26             items = new List<Item>();
27 
28             Reset();
29         }
30 
Reset()31         public void Reset()
32         {
33             Array.Copy(resetValue, previousState, previousState.Length);
34         }
35 
AcceptState(bool[] state)36         public int AcceptState(bool[] state)
37         {
38             var result = -1;
39 
40             loggingParent?.Log(LogLevel.Noisy, "Accepting new state [{0}]; previous state [{1}]", string.Join(", ", state), string.Join(", ", previousState));
41 
42             for(var i = 0; i < items.Count; i++)
43             {
44                 if(items[i].patternDecoder(previousState, state))
45                 {
46                     loggingParent?.Log(LogLevel.Noisy, "Pattern {0} decoded", items[i].name);
47                     if(items[i].action != null)
48                     {
49                         items[i].action(state);
50                     }
51                     result = i;
52                     break;
53                 }
54             }
55 
56             Array.Copy(state, previousState, previousState.Length);
57             return result;
58         }
59 
RegisterPatternHandler(Func<bool[], bool[], bool> patternDecoder, Action<bool[]> action = null, string name = null)60         public int RegisterPatternHandler(Func<bool[], bool[], bool> patternDecoder, Action<bool[]> action = null, string name = null)
61         {
62             items.Add(new Item { patternDecoder = patternDecoder, action = action, name = name });
63             return items.Count - 1;
64         }
65 
66         private readonly List<Item> items;
67         private readonly IPeripheral loggingParent;
68 
69         private readonly bool[] previousState;
70         private readonly bool[] resetValue;
71 
72         private struct Item
73         {
74             public Func<bool[], bool[], bool> patternDecoder;
75             public Action<bool[]> action;
76             public string name;
77         }
78     }
79 }
80