Пример #1
0
 public int Menu()
 {
     while (true)
     {
         //Console.Clear();
         SmartLog.WriteLine("\nHID Menu");
         SmartLog.WriteLine("--------------------------------------------------------");
         SmartLog.WriteLine("1. Increment Connected Device");
         SmartLog.WriteLine("2. Decrement Connected Device");
         SmartLog.WriteLine("3. Save");
         var consoleKey = Console.ReadKey();
         if (consoleKey.KeyChar == '1')
         {
             return(1);
         }
         if (consoleKey.KeyChar == '2')
         {
             return(2);
         }
         if (consoleKey.KeyChar == '3')
         {
             return(3);
         }
     }
 }
Пример #2
0
        private static async Task DisplayDataAsync()
        {
            var bytes = await DeviceConnectionExample.WriteAndReadFromDeviceAsync();

            Console.Clear();
            SmartLog.WriteLine("Device connected. Output:");
            DisplayData(bytes);
        }
Пример #3
0
        public async Task <LoopResponse> Go(int menuOption)
        {
            var loopResponse = new LoopResponse
            {
                Selection = menuOption
            };

            switch (menuOption)
            {
            case 1:
                try
                {
                    //await DeviceConnectionExample.InitializeTrezorAsync();
                    await IncrementAsync();

                    //DeviceConnectionExample.Dispose();
                }
                catch (Exception ex)
                {
                    Console.Clear();
                    SmartLog.WriteLine(ex.ToString());
                }

                return(await Task.FromResult(loopResponse));

            case 2:
                try
                {
                    //await DeviceConnectionExample.InitializeTrezorAsync();
                    await DecrementAsync();

                    // DeviceConnectionExample.Dispose();
                }
                catch (Exception ex)
                {
                    Console.Clear();
                    SmartLog.WriteLine(ex.ToString());
                }
                return(await Task.FromResult(loopResponse));

            case 3:
                try
                {
                    // await DeviceConnectionExample.InitializeTrezorAsync();
                    await SaveAsync();

                    //DeviceConnectionExample.Dispose();
                }
                catch (Exception ex)
                {
                    Console.Clear();
                    SmartLog.WriteLine(ex.ToString());
                }
                return(await Task.FromResult(loopResponse));
            }
            return(await Task.FromResult(loopResponse));
        }
Пример #4
0
        public static async Task <int> IncrementOrDecrementStrain(SgAdjust sgAdjust)
        {
            if (_deviceCount == 0)
            {
                await Init();
            }


            // set the SPI xFer params for I/O expander
            uint baudRate2      = 250000; //1000000
            uint idleCsVal2     = 0x1ff;
            uint activeCsVal2   = 0x1fd;  //GP1 CS PIN, remaining pins are GP //0x1ee GP4 and GP0 set as active low CS
            uint csToDataDly2   = 0;
            uint dataToDataDly2 = 0;
            uint dataToCsDly2   = 0;
            uint txFerSize2     = 3;    // I/O expander xFer size set to 4
            byte spiMd2         = 0;
            uint csMask4        = 0x02; //GP1 as CS  // 0x10 set GP4 as CS

            byte[] txData = new byte[3], rxData = new byte[3];
            switch (sgAdjust)
            {
            // set the expander config params
            case SgAdjust.Increment:
                txData[0] = 0x60;
                break;

            case SgAdjust.Decrement:
                txData[0] = 0xE0;
                break;

            case SgAdjust.Save:
                txData[0] = 0x20;
                //SmartLog.WriteLine(
                //    $"txData:{txData.ToHex()}\nrxData:{rxData.ToHex()}\nbaudRate2:{baudRate2}\ntxFerSize2:{txFerSize2}\ncsMask4:{csMask4}\nidleCsVal2:{idleCsVal2}\nactiveCsVal2:{activeCsVal2}\ncsToDataDly2:{csToDataDly2}\ndataToCsDly2:{dataToCsDly2}\ndataToDataDly2:{dataToDataDly2}\nspiMd2:{spiMd2}");
                break;
            }

            txData[1] = 0x00;
            txData[2] = 0x00;
            // send the data
            // use the extended SPI xFer API first time in order to set all the parameters
            // the subsequent xFer with the same device may use the simple API in order to save CPU cycles
            _response = MCP2210.M_Mcp2210_xferSpiDataEx(_deviceHandle, txData, rxData, ref baudRate2, ref txFerSize2,
                                                        csMask4, ref idleCsVal2, ref activeCsVal2, ref csToDataDly2,
                                                        ref dataToCsDly2, ref dataToDataDly2, ref spiMd2);
            if (_response != MCP2210.M_E_SUCCESS)
            {
                MCP2210.M_Mcp2210_Close(_deviceHandle);
                SmartLog.WriteErrorLine($"Sg ({sgAdjust.ToString()}) transfer error: " + _response);
                _deviceCount = 0;
                return(_response);
            }

            SmartLog.WriteLine($"Sg ({sgAdjust.ToString()}) transfer response: " + _response);
            return(0);
        }
Пример #5
0
        private static void Greet()
        {
            ConsoleColor BorderColor = ConsoleColor.Cyan;

            Console.ForegroundColor = BorderColor;
            SmartLog.WriteLine(" Analog Front End (AFE) Calibration");
            SmartLog.WriteLine("--------------------------------------------------------");
            SmartLog.WriteLine("--------------------------------------------------------");
        }
Пример #6
0
        public static async Task DecrementAsync()
        {
            var writeBuffer = new byte[3];

            writeBuffer[0] = 0xE0;
            writeBuffer[1] = 0x00;
            writeBuffer[2] = 0x00;
            var responseBytes = await DeviceConnectionExample.WriteToDecrementAsync(writeBuffer);

            SmartLog.WriteLine($"Decrement Command:\n\t{writeBuffer.ToHex()}");
            SmartLog.WriteLine($"Device Output:\n\t{responseBytes.ToHex()}");
        }
Пример #7
0
 private static async void _DeviceConnectionExample_TrezorInitialized(object sender, EventArgs e)
 {
     try
     {
         Console.Clear();
         await DisplayDataAsync();
     }
     catch (Exception ex)
     {
         Console.Clear();
         SmartLog.WriteLine(ex.ToString());
     }
 }
Пример #8
0
        public static async Task SaveAsync()
        {
            var writeBuffer = new byte[3];

            writeBuffer[0] = 0x20;
            writeBuffer[1] = 0x00;
            writeBuffer[2] = 0x00;
            var responseBytes = await DeviceConnectionExample.WriteToSaveAsync(writeBuffer);

            //Console.Clear();
            SmartLog.WriteLine($"Save Command:\n\t{writeBuffer.ToHex()}");
            SmartLog.WriteLine($"Device Output:\n\t{responseBytes.ToHex()}");
            //DisplayData(bytes);
        }
Пример #9
0
        private static void PrintCollectResponse(List <Sensor> sensors)
        {
            ConsoleColor borderColor = ConsoleColor.Yellow;

            Console.ForegroundColor = borderColor;
            foreach (var sensor in sensors)
            {
                SmartLog.WriteLine(
                    $"{sensor.Afe} ({sensor.Data.Count} samples): {sensor.Type}:{Math.Truncate(sensor.Data.Average(x => x.Value))}," +
                    $" Quantized: {Math.Truncate(sensor.Data.Select(x => BitConverter.ToUInt16(x.Bytes, 0)).Average(x => x))}");
            }

            borderColor             = ConsoleColor.White;
            Console.ForegroundColor = borderColor;
        }
Пример #10
0
 public static byte[] HexToByteArray(this string hex)
 {
     try
     {
         byte[] bytes = Enumerable.Range(0, hex.Length)
                        .Where(x => x % 2 == 0)
                        .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                        .ToArray();
         return(bytes);
     }
     catch (Exception e)
     {
         SmartLog.WriteLine(e.Message);
         return(null);
     }
 }
Пример #11
0
        public static async Task <int> Init()
        {
            _deviceCount = MCP2210.M_Mcp2210_GetConnectedDevCount(DefaultVid, DefaultPid);
            SmartLog.WriteLine(_deviceCount + " SPI Module Device(s) found");
            if (_deviceCount <= 0)
            {
                return(_response);
            }
            StringBuilder path = new StringBuilder();

            _deviceHandle = MCP2210.M_Mcp2210_OpenByIndex(DefaultVid, DefaultPid, 0, path);
            _response     = MCP2210.M_Mcp2210_GetLastError();
            if (_response != MCP2210.M_E_SUCCESS)
            {
                SmartLog.WriteErrorLine("Failed to open connection");
                return(await Task.FromResult(-1));
            }

            return(_response);
        }
Пример #12
0
        private static bool DetectComPort()
        {
            _defaultComPort = _smartPort.GetPort("0403", "6001");
            if (string.IsNullOrWhiteSpace(_defaultComPort))
            {
                SmartLog.WriteLine("Available COM ports");
                SmartLog.WriteLine("--------------------------------------------------------");

                int i = 1;
                int selectedOption;
                var comports = ComPortInfo.GetComPortsInfo();
                comports.ForEach(x =>
                {
                    SmartLog.WriteLine($"{i}) {x.Name}:{x.Description}");
                    i++;
                });
                SmartLog.WriteLine("\nSelect COM Port (Example: Type 1 and press enter for first COM port):");
                while (!int.TryParse(Console.ReadLine(), out selectedOption) ||
                       (comports.ElementAtOrDefault(selectedOption - 1) == null))
                {
                    SmartLog.WriteLine("Invalid Entry\nPlease Enter from available options");
                }

                var selectedComPort = comports.ElementAtOrDefault(selectedOption - 1);
                if (selectedComPort == null)
                {
                    SmartLog.WriteLine("Invalid Entry\nPlease Enter from available options");
                    Console.ReadKey();
                    return(false);
                }

                _defaultComPort = selectedComPort.Name;
            }

            return(true);
        }
Пример #13
0
        private static void GetBoardId()
        {
            if (!string.IsNullOrWhiteSpace(_options.BoardId) && _options.BoardId.HexToByteArray() != null)
            {
                _boardId = _options.BoardId.HexToByteArray()[0];
                return;
            }
            SmartLog.WriteLine("\nPlease Enter Interface Board Id (in Hex):");
            bool isValidBoardId = false;

            while (!isValidBoardId)
            {
                var bytes = Console.ReadLine().HexToByteArray();
                if (bytes == null)
                {
                    SmartLog.WriteLine("\nInvalid Hex. Please re-enter");
                }
                else
                {
                    _boardId       = bytes[0];
                    isValidBoardId = true;
                }
            }
        }
Пример #14
0
 private static void _DeviceConnectionExample_TrezorDisconnected(object sender, EventArgs e)
 {
     Console.Clear();
     SmartLog.WriteLine("Disconnected.");
     DisplayWaitMessage();
 }
Пример #15
0
 private static void DisplayWaitMessage()
 {
     SmartLog.WriteLine("Waiting for device to be plugged in...");
 }
Пример #16
0
 private static void DisplayData(byte[] readBuffer)
 {
     SmartLog.WriteLine(string.Join(" ", readBuffer));
     Console.ReadKey();
 }
Пример #17
0
        // ReSharper disable once UnusedParameter.Local
        static async Task Main(string[] args)
        {
            Console.Clear();
            Parser.Default.ParseArguments <Options>(args)
            .WithParsed(o =>
            {
                _options = o;
                SmartLog.WriteLine(!string.IsNullOrWhiteSpace(o.BoardId)
                        ? $"Entered IFB Board Id (in Hex). Current Arguments: --ifb {o.BoardId.ToUpper()}"
                        : $"No IFB Board Id passed. Current Arguments: --ifb");
                SmartLog.WriteLine(o.PrintRequest
                        ? $"Print Request enabled. Current Arguments: --req {o.PrintRequest}"
                        : $"Print Request disabled. Current Arguments: --req {o.PrintRequest}");
                SmartLog.WriteLine(o.PrintResponse
                        ? $"Print Response enabled. Current Arguments: --res {o.PrintResponse}"
                        : $"Print Response disabled. Current Arguments: --res {o.PrintResponse}");
                SmartLog.WriteLine(o.PrintDataPortConfig
                        ? $"Print Data Port Config enabled. Current Arguments: --conf {o.PrintDataPortConfig}"
                        : $"Print Data Port Config disabled. Current Arguments: --conf {o.PrintDataPortConfig}");
                SmartLog.WriteLine(o.Model == 1 || o.Model == 2
                        ? $"Entered Model. Current Arguments: --mdl {o.Model + (o.Model== 1 ? ":Ax-Sg": ":Sg-Sg")}"
                        : $"No Model entered. Current Arguments: --mdl");
            });

            if (args != null && args.Any() && args[0].Equals("--help", StringComparison.InvariantCultureIgnoreCase))
            {
                return;
            }
            if (args != null && args.Any() && args[0].Equals("--version", StringComparison.InvariantCultureIgnoreCase))
            {
                return;
            }

            Greet();
            Init();
            if (!DetectComPort())
            {
                return;
            }
            GetBoardId();
            Console.WriteLine();
            DataPortConfig defaultDataPortConfig = _smartPort.GetDefaultDataPortConfig();
            await _smartPort.Init(_boardId, _defaultComPort, _options);

            if (!_smartPort.Start())
            {
                return;
            }
            var readDataPortConfig = _smartPort.ReadDataPortConfig();
            //CompareDataPortConfig(readDataPortConfig, defaultDataPortConfig);
            var portTask = _smartPort.Go(menuOption: CommandType.Collect);

            while (portTask.Result.Selection != CommandType.Exit)
            {
                switch (portTask.Result.Selection)
                {
                case CommandType.JustCollect:
                {
                    if (portTask.Result.ReturnObject != null)
                    {
                        var sensors = ((List <Sensor>)portTask.Result.ReturnObject);
                        PrintCollectResponse(sensors);
                    }
                    break;
                }

                case CommandType.Collect:
                {
                    if (portTask.Result.ReturnObject != null)
                    {
                        var sensors = ((List <Sensor>)portTask.Result.ReturnObject);
                        if (sensors[1].Data != null && sensors[1].Data.Any())
                        {
                            var channelThreeQuantized =
                                //Math.Truncate(sensors[1].Data.Select(x => BitConverter.ToUInt16(x.Bytes, 0))
                                //    .Average(x => x));
                                Math.Truncate(sensors[1].Data.Average(x => x.Value));
                            _isTip = channelThreeQuantized < 300 || channelThreeQuantized > 3800;
                        }

                        PrintCollectResponse(sensors);
                        //if (_options.Model.Equals(2))
                        //    sensors = sensors.Skip(2).Take(2).ToList();
                        await AdjustStrain(readDataPortConfig, sensors);
                        await AdjustAx(readDataPortConfig, sensors);
                    }

                    break;
                }

                case CommandType.ReadDataPort:
                {
                    if (portTask.Result.ReturnObject != null)
                    {
                        var dataPortConfig = ((DataPortConfig)portTask.Result.ReturnObject);
                        CompareDataPortConfig(dataPortConfig, defaultDataPortConfig);
                    }

                    break;
                }
                }

                //portTask = _smartPort.Go(menuOption: _smartPort.Menu());
                portTask   = _smartPort.Go(menuOption: _smartPort.Menu(_printMenu));
                _printMenu = false;
            }

            //SmartLog.WriteLine("Type exit to quite\n");
            //while (!Convert.ToString(Console.ReadLine()).Equals("exit", StringComparison.OrdinalIgnoreCase))
            //{
            //    SmartLog.WriteLine("Unknown command\n");
            //}

            //_smartPort.PowerOff();
        }