Example #1
0
        /// <summary>
        /// Gets the analog reference options.
        /// </summary>
        public static void GetAnalogReference()
        {
            var command   = new SendCommand((int)Command.GetAnalogReference, (int)Command.GetAnalogReference, 500);
            var returnVal = _cmdMessenger.SendCommand(command);

            if (returnVal.Ok)
            {
                AnalogReferences.Clear();
                for (int i = 0; i < (returnVal.Arguments.Length / 2); i++)
                {
                    AnalogReferences.Add(returnVal.ReadStringArg(), returnVal.ReadInt16Arg());
                }
                LastCommunication = DateTime.Now;
            }
        }
        // Loop function
        public void Loop()
        {
            // Create command
            var command = new SendCommand((int)Command.SetLed, _ledState);

            // Send command
            _cmdMessenger.SendCommand(command);

            Console.Write("Turning led ");
            Console.WriteLine(_ledState?"on":"off");

            // Wait for 1 second and repeat
            Thread.Sleep(1000);
            _ledState = !_ledState;   // Toggle led state
        }
Example #3
0
        /// <summary>
        /// Gets the number analog pins.
        /// </summary>
        public static void GetNumberAnalogPins()
        {
            var command   = new SendCommand((int)Command.GetNumberAnalogPins, (int)Command.GetNumberAnalogPins, 1000);
            var returnVal = _cmdMessenger.SendCommand(command);

            if (returnVal.Ok)
            {
                NumberOfAnalogPins = returnVal.ReadUInt32Arg();
                LastCommunication  = DateTime.Now;
            }
            else
            {
                NumberOfAnalogPins = uint.MaxValue;
            }
        }
Example #4
0
        // Loop function
        public void Loop()
        {
            for (int i = 0; i < 100; i++)
            {
                // Create command FloatAddition, which will wait for a return command FloatAdditionResult
                var command = new SendCommand((int)Command.FloatAddition, (int)Command.FloatAdditionResult, 1000);

                // Add 2 float command arguments
                var a = 3.14F;
                var b = 2.71F;
                command.AddArgument(a);
                command.AddArgument(b);

                // Send command
                var floatAdditionResultCommand = _cmdMessenger.SendCommand(command);

                // Check if received a (valid) response
                if (floatAdditionResultCommand.Ok)
                {
                    // Read returned argument
                    var sum  = floatAdditionResultCommand.ReadFloatArg();
                    var diff = floatAdditionResultCommand.ReadFloatArg();

                    // Compare with sum of sent values
                    var errorSum  = sum - (a + b);
                    var errorDiff = diff - (a - b);

                    //Console.WriteLine("Received sum {0}, difference of {1}", sum, diff);
                    ///Console.WriteLine("with errors {0} and {1}, respectively", errorSum, errorDiff);

                    if (errorDiff < 1e-6 && errorSum < 1e-6)
                    {
                        Console.WriteLine("OK: " + i);
                    }
                    else
                    {
                        Console.WriteLine("FAILED: " + i);
                    }
                }
                else
                {
                    Console.WriteLine("No response!");
                }

                //Thread.Sleep(1);
            }
            Console.WriteLine("FINISHED");
        }
Example #5
0
        /// <summary>
        /// Gets the number digital pins.
        /// </summary>
        public static void GetNumberDigitalPins()
        {
            var command   = new SendCommand((int)Command.GetNumberDigitalPins, (int)Command.GetNumberDigitalPins, 1000);
            var returnVal = _cmdMessenger.SendCommand(command);

            if (returnVal.Ok)
            {
                NumberOfDigitalPins = returnVal.ReadUInt32Arg();
                LastCommunication   = DateTime.Now;
            }
            else
            {
                //in case the arduino did not respond
                NumberOfDigitalPins = uint.MaxValue;
            }
        }
        protected override bool HandleSendCommand(SendCommand Command)
        {
            ServerSendCommand sendCommand = (ServerSendCommand)Command;
            UDPClient         client      = (UDPClient)sendCommand.Client;

            if (!client.IsReady)
            {
                return(false);
            }

            client.Statistics.AddBandwidthOut(Command.Buffer.Size);

            SendOverSocket(client.EndPoint, Command.Buffer);

            return(true);
        }
Example #7
0
        private void ParameterRefresh()
        {
            _sendCommand = SendCommand.None;
            _deviceData  = new DeviceData[NativeMethods.DeviceCount];
            _callback    = new HighSpeedDataCallBack(ReceiveHighSpeedData);

            for (int i = 0; i < NativeMethods.DeviceCount; i++)
            {
                _deviceData[i] = new DeviceData();
            }
            _profileInfo = new LJV7IF_PROFILE_INFO[NativeMethods.DeviceCount];

            currentBatch = new BatchData();
            CPGap        = new CalculationParameter(0, 2, 10);
            CPSeam       = new CalculationParameter(0, 2, 10);
        }
Example #8
0
        public MainWindowViewModel()
        {
            SendCommand.Subscribe(_ =>
            {
                MySetting.Instance.ServerIPAddress = ServerIPAddress.Value;

                using (var client = new TcpClient(ServerIPAddress.Value, __controllPort))
                {
                    var stream  = client.GetStream();
                    var message = Encoding.ASCII.GetBytes((__counter++).ToString());
                    stream.Write(message);
                }
            });

            ServerIPAddress.Value = MySetting.Instance.ServerIPAddress;
        }
Example #9
0
 public ChatViewmodel(Connection connection, User user, Window window) : base(window)
 {
     ExitWindowCommand = new ExitWindowCommand(this);
     OpenWindowCommand = new NewConnectionCommand(this);
     SendCommand       = new SendCommand(this);
     SendImageCommand  = new SendImageCommand(this);
     SendBuzzCommand   = new SendBuzzCommand(this);
     Connection        = connection;
     User     = user;
     ThisMsg  = "";
     Messages = new ObservableCollection <Packet>();
     connection.Actions["Message"] = (Action <Packet>)DisplayMessage;
     connection.Actions["Image"]   = (Action <Packet>)DisplayImage;
     connection.Actions["Buzz"]    = (Action <Packet>)RecieveBuzz;
     connection.startReciving();
 }
Example #10
0
        // Set the goal temperature on the embedded controller
        public void SetGoalTemperature(double goalTemperature)
        {
            _goalTemperature = goalTemperature;

            // Create command to start sending data
            var command = new SendCommand((int)Command.SetGoalTemperature, _goalTemperature);

            // Collapse this command if needed using CollapseCommandStrategy
            // This strategy will avoid duplicates of this command on the queue: if a SetGoalTemperature command is
            // already on the queue when a new one is added, it will be replaced at its current queue-position.
            // Otherwise the command will be added to the back of the queue.
            //
            // This will make sure that when the slider raises a lot of events that each set a new goal temperature, the
            // controller will not start lagging.
            _cmdMessenger.QueueCommand(new CollapseCommandStrategy(command));
        }
Example #11
0
        public override void Send(SendOrPostCallback d, object state)
        {
            var send = new SendCommand {
                d = d, state = state
            };

            lock (send)
            {
                Post(SendCommand.Call, send);
                Monitor.Wait(send);
            }
            if (send.ex != null)
            {
                throw send.ex;
            }
        }
Example #12
0
 private ReceivedCommand InteractInternal(SendCommand command)
 {
     while (true)
     {
         var resultCommand = messenger.SendCommand(command);
         if (resultCommand.Ok)
         {
             return(resultCommand);
         }
         else
         {
             System.Console.WriteLine($"[{DateTime.Now.ToString("HH':'mm':'ss'.'fffffff")}] [SERIAL] !! NO RESPONSE!");
             Update();
         }
     }
 }
        static MimeMessage CreateMessage(SendCommand command)
        {
            var message = new MimeMessage();

            message.From.Add(CreateAddress(command.From !));

            if (command.ReplyTo != null)
            {
                message.ReplyTo.Add(CreateAddress(command.ReplyTo));
            }

            foreach (var to in command.To !)
            {
                message.To.Add(CreateAddress(to));
            }

            if (command.Cc != null)
            {
                foreach (var cc in command.Cc !)
                {
                    message.Cc.Add(CreateAddress(cc));
                }
            }

            if (command.Bcc != null)
            {
                foreach (var bcc in command.Bcc !)
                {
                    message.Bcc.Add(CreateAddress(bcc));
                }
            }

            message.Subject = command.Subject;

            var bodyBuilder = new BodyBuilder();

            if (!string.IsNullOrEmpty(command.PlainTextBody))
            {
                bodyBuilder.TextBody = command.PlainTextBody;
            }
            if (!string.IsNullOrEmpty(command.HtmlBody))
            {
                bodyBuilder.HtmlBody = command.HtmlBody;
            }
            message.Body = bodyBuilder.ToMessageBody();
            return(message);
        }
Example #14
0
        private async void OnUnsubscribeCommand()
        {
            canSubscribe = true;
            SubscribeCommand.RaiseCanExecuteChanged();
            canUnsubscribe = false;
            UnsubscribeCommand.RaiseCanExecuteChanged();

            await hub.Invoke <int>("Unsubscribe", new object[] { ClientId });

            if (connection.State == ConnectionState.Connected)
            {
                connection.Stop();
            }

            canSend = false;
            SendCommand.RaiseCanExecuteChanged();
        }
        private const float SeriesBase = 1111111.111111F;       // Base of values to return: SeriesBase * (0..SeriesLength-1)

        // ------------------ M A I N  ----------------------

        // Setup function
        public void Setup()
        {
            // Create Serial Port object
            _serialTransport = new SerialTransport
            {
                CurrentSerialSettings = { PortName = "COM6", BaudRate = 115200 } // object initializer
            };

            // Initialize the command messenger with the Serial Port transport layer
            _cmdMessenger = new CmdMessenger(_serialTransport);

            // Attach the callbacks to the Command Messenger
            AttachCommandCallBacks();

            // Start listening
            _cmdMessenger.StartListening();

            _receivedPlainTextCount = 0;

            // Send command requesting a series of 100 float values send in plain text
            var commandPlainText = new SendCommand((int)Command.RequestPlainTextFloatSeries);

            commandPlainText.AddArgument(SeriesLength);
            commandPlainText.AddArgument(SeriesBase);
            // Send command
            _cmdMessenger.SendCommand(commandPlainText);

            // Now wait until all values have arrived
            while (!_receivePlainTextFloatSeriesFinished)
            {
            }

            // Send command requesting a series of 100 float values send in plain text
            var commandBinary = new SendCommand((int)Command.RequestBinaryFloatSeries);

            commandBinary.AddBinArgument((UInt16)SeriesLength);
            commandBinary.AddBinArgument((Single)SeriesBase);

            // Send command
            _cmdMessenger.SendCommand(commandBinary);

            // Now wait until all values have arrived
            while (!_receiveBinaryFloatSeriesFinished)
            {
            }
        }
Example #16
0
        // Loop function
        public void Loop()
        {
            // Create command FloatAddition, which will wait for a return command FloatAdditionResult
            var command = new SendCommand((int)Command.FloatAddition, (int)Command.FloatAdditionResult, 1000);

            // Add 2 float command arguments
            var a = 3.14F;
            var b = 2.71F;

            command.AddArgument(a);
            command.AddArgument(b);

            // Send command
            var floatAdditionResultCommand = _cmdMessenger.SendCommand(command);

            // Check if received a (valid) response
            if (floatAdditionResultCommand.Ok)
            {
                // Read returned argument
                var sum  = floatAdditionResultCommand.ReadFloatArg();
                var diff = floatAdditionResultCommand.ReadFloatArg();

                // Compare with sum of sent values
                var errorSum  = sum - (a + b);
                var errorDiff = diff - (a - b);

                Console.WriteLine("Received sum {0}, difference of {1}", sum, diff);
                Console.WriteLine("with errors {0} and {1}, respectively", errorSum, errorDiff);

                if (errorDiff < 1e-6 && errorSum < 1e-6)
                {
                    Console.WriteLine("Seems to be correct!");
                }
                else
                {
                    Console.WriteLine("Does not seem to be correct!");
                }
            }
            else
            {
                Console.WriteLine("No response!");
            }

            // Stop running loop
            RunLoop = false;
        }
Example #17
0
        public SettingsViewModel(
            ISettingsModel settingsModel,
            LoadCommand loadCommand,
            SaveCommand saveCommand,
            SendCommand sendCommand)
        {
            this.settingsModel = settingsModel;

            this.Fields      = new ObservableCollection <FieldViewModel>();
            this.LoadCommand = loadCommand;
            this.SaveCommand = saveCommand;
            this.SendCommand = sendCommand;

            this.settingsModel.EepromFields.ForEach(f => {
                this.Fields.Add(new FieldViewModel(f, settingsModel));
            });
        }
        // ------------------ MAIN  ----------------------

        // Setup function
        public void Setup(ChartForm chartForm)
        {
            // getting the chart control on top of the chart form.
            _chartForm = chartForm;

            // Set up chart
            _chartForm.SetupChart();

            // Create Serial Port object
            // Note that for some boards (e.g. Sparkfun Pro Micro) DtrEnable may need to be true.
            _serialTransport = new SerialTransport
            {
                CurrentSerialSettings = { PortName = "COM6", BaudRate = 115200, DtrEnable = false } // object initializer
            };

            // Initialize the command messenger with the Serial Port transport layer
            _cmdMessenger = new CmdMessenger(_serialTransport)
            {
                BoardType = BoardType.Bit16 // Set if it is communicating with a 16- or 32-bit Arduino board
            };

            // Tell CmdMessenger to "Invoke" commands on the thread running the WinForms UI
            _cmdMessenger.SetControlToInvokeOn(chartForm);

            // Set Received command strategy that removes commands that are older than 1 sec
            _cmdMessenger.AddReceiveCommandStrategy(new StaleGeneralStrategy(1000));

            // Attach the callbacks to the Command Messenger
            AttachCommandCallBacks();

            // Attach to NewLinesReceived for logging purposes
            _cmdMessenger.NewLineReceived += NewLineReceived;

            // Attach to NewLineSent for logging purposes
            _cmdMessenger.NewLineSent += NewLineSent;

            // Start listening
            _cmdMessenger.StartListening();

            // Send command to start sending data
            var command = new SendCommand((int)Command.StartLogging);

            // Send command
            _cmdMessenger.SendCommand(command);
        }
        /// <summary>
        /// Request to light a given number of leds for a given player.
        /// </summary>
        /// <param name="ledNumber">Led number.</param>
        /// <param name="playerNumber">Player number (1 or 2)</param>
        public void LightUpLed(int ledNumber, int playerNumber)
        {
            if (ledNumber < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(ledNumber), "negative led count");
            }
            if (playerNumber != 1 && playerNumber != 2)
            {
                throw new ArgumentOutOfRangeException(nameof(playerNumber), "player does not exists");
            }

            string[] arguments = new string[2];
            arguments[0] = ledNumber.ToString();
            arguments[1] = playerNumber.ToString();
            var command = new SendCommand((int)Command.LightUpLed, arguments, (int)Command.Acknowledge, 1000);

            _cmdMessenger.SendCommand(command);
        }
        /// <summary>
        /// Sets the color of the player.
        /// </summary>
        /// <param name="playerNumber">Player number.</param>
        /// <param name="color">HEX string of the color.</param>
        public void SetPlayerColor(int playerNumber, string color)
        {
            if (playerNumber != 1 && playerNumber != 2)
            {
                throw new ArgumentOutOfRangeException(nameof(playerNumber), "player does not exists");
            }
            if (color.Length != 6)
            {
                throw new ArgumentException(nameof(color), "not a valid hex color");
            }

            string[] arguments = new string[2];
            arguments[0] = playerNumber.ToString();
            arguments[1] = color;
            var command = new SendCommand((int)Command.SetPlayerColor, arguments, (int)Command.Acknowledge, 1000);

            _cmdMessenger.SendCommand(command);
        }
Example #21
0
 /// <summary>
 /// Sets the pin.
 /// </summary>
 /// <param name="nr">Nr.</param>
 /// <param name="mode">Mode.</param>
 /// <param name="state">State.</param>
 public static void SetPin(uint nr, PinMode mode, DPinState state)
 {
                 #if !FAKESERIAL
     var command = new SendCommand((int)Command.SetPin, (int)Command.SetPin, 100);
     command.AddArgument((UInt16)nr);
     command.AddArgument((Int16)mode);
     command.AddArgument((Int16)state);
     var ret = _cmdMessenger.SendCommand(command);
     if (ret.Ok)
     {
         if (!(nr == (uint)ret.ReadInt32Arg() && (Int16)mode == ret.ReadInt16Arg() && (Int16)state == ret.ReadInt16Arg()))
         {
             Console.Error.WriteLine(DateTime.Now.ToString("HH:mm:ss tt zz") + "\t" + nr + "\t" + mode + "\t" + state);
         }
         LastCommunication = DateTime.Now;
     }
                 #endif
 }
Example #22
0
        public void SendPrintCommand(UInt16 box, UInt16 to_feed)
        {
            Console.WriteLine("Sending Print command to box {0} and feed {1}", box, to_feed);
            // Send the command, wait for 1s for the the acknowledge command
            SendCommand command = new SendCommand((int)Command.Print, (int)Command.AcknowledgePrint, 1000);

            command.AddArgument(box);
            command.AddArgument(to_feed);

            ReceivedCommand rec_command = _cmdMessenger.SendCommand(command);

            var unique_id = rec_command.ReadUInt16Arg();

            box     = rec_command.ReadUInt16Arg();
            to_feed = rec_command.ReadUInt16Arg();

            Console.WriteLine("Acknowledge Print command with unique id {0} to box {1} and feed {2}", unique_id, box, to_feed);
        }
Example #23
0
        public int InvokeCommand(SendCommand o)
        {
            var name = o.HostName ?? _settings.DefaultHost;

            if (name is null)
            {
                Console.WriteLine("Default host is not defined".Error());
                return(1);
            }

            var host = _settings.Hosts.FirstOrDefault(e => e.Name == name);

            if (host is null)
            {
                Console.WriteLine($"Can't find host: {name}".Error());
                return(1);
            }
            return(0);
        }
Example #24
0
        // Loop function
        public void Loop()
        {
            _count++;

            // Create command
            var command = new SendCommand((int)Command.SetLed, _ledState);

            // Send command
            _cmdMessenger.SendCommand(command);

            // Wait for 1 second and repeat
            Thread.Sleep(1000);
            _ledState = !_ledState;                                        // Toggle led state

            if (_count > 100)
            {
                RunLoop = false;                                           // Stop loop after 100 rounds
            }
        }
        public void Update(int data)
        {
            if (_data == data)
            {
                return;
            }
            _data = (byte)data;
            // Prepare command
            var command = new SendCommand((int)EnumOperationTypes.LedOutput);

            command.AddArgument(_id);
            command.AddArgument(_data);
            ReceivedCommand resultCommand = _cmdMessenger.SendCommand(command);

            if (!resultCommand.Ok)
            {
                // Log
            }
        }
Example #26
0
        // Toggle live video playback on or off
        void UpdateLiveVideoPlayback(bool useSample)
        {
            if (AllowUICommandUpdates)
            {
                Task.Run(() =>
                {
                    // Create a message payload
                    var items        = new Dictionary <string, object>();
                    items["Command"] = "SetUseSampleVideo";
                    items["Value"]   = useSample;
                    var msg          = MessageFactory.Create("ServerCommand", (Int32)Message.MessageType.ServerCommand, items);

                    // Send command
                    var cmd  = new SendCommand();
                    bool bOK = cmd.SendCommandMessage(ref msg, out string error);
                    Debug.Assert(bOK, error);
                });
            }
        }
        // Signal the embedded controller to stop sending temperature data.
        public bool StopAcquisition()
        {
            // Send command to stop sending data
            var command = new SendCommand((int)Command.StopLogging, (int)Command.Acknowledge, 2500);

            // Wait for an acknowledgment that data is being sent. Clear both the send and receive queue until the acknowledgment is received
            _chartForm.LogMessage(@"Send command - Stop acquisition");
            var receivedCommand = _cmdMessenger.SendCommand(command, SendQueue.ClearQueue, ReceiveQueue.ClearQueue);

            if (receivedCommand.Ok)
            {
                AcquisitionStarted = false;
            }
            else
            {
                _chartForm.LogMessage(@" Failure > no OK received from controller");
            }
            return(receivedCommand.Ok);
        }
    public void SetButtonColor(int index, Color color)
    {
        if (cmdMessenger == null)
        {
            return;
        }

        short r = (short)Mathf.RoundToInt(color.r * intensity);
        short g = (short)Mathf.RoundToInt(color.g * intensity);
        short b = (short)Mathf.RoundToInt(color.b * intensity);

        var command = new SendCommand((int)Command.SetButtonColorRequest);

        command.AddArgument((short)index);
        command.AddArgument(r);
        command.AddArgument(g);
        command.AddArgument(b);
        cmdMessenger.SendCommand(command);
    }
Example #29
0
        public string Move(int mov)
        {
            tl.LogMessage("Transmitting", "");
            SendCommand command = new SendCommand((int)Command.Move, (int)Command.Acknowledge, 2000);

            command.AddArgument(mov);
            rcmd = _cmdMessenger.SendCommand(command);
            if (rcmd.Ok)
            {
                tl.LogMessage("Transmit", "true");
                System.Threading.Thread.Sleep(mov);
            }
            else
            {
                tl.LogMessage("Transmit", "false");
            }

            return(status);
        }
Example #30
0
        /// <summary>
        /// Constructor
        /// </summary>
        public MainForm()
        {
            InitializeComponent();

            // Field initialization
            _sendCommand = SendCommand.None;
            _deviceData = new DeviceData[NativeMethods.DeviceCount];
            _measureDatas = new List<MeasureData>();
            _callback = new HighSpeedDataCallBack(ReceiveHighSpeedData);
            _callbackOnlyCount = new HighSpeedDataCallBack(CountProfileReceive);
            _deviceStatusLabels= new Label[] {
                _lblDeviceStatus0, _lblDeviceStatus1, _lblDeviceStatus2,
                _lblDeviceStatus3, _lblDeviceStatus4, _lblDeviceStatus5};

            _receivedProfileCountLabels = new Label[] {
                _lblReceiveProfileCount0, _lblReceiveProfileCount1, _lblReceiveProfileCount2,
                _lblReceiveProfileCount3, _lblReceiveProfileCount4, _lblReceiveProfileCount5};

            for (int i = 0; i < NativeMethods.DeviceCount; i++)
            {
                _deviceData[i] = new DeviceData();
                _deviceStatusLabels[i].Text = _deviceData[i].GetStatusString();
            }
            _profileInfo = new LJV7IF_PROFILE_INFO[NativeMethods.DeviceCount];

            // Communication button comment setting
            SetCommandBtnString();

            // Control initialization
            _cmbMeasureX.DataSource = GetMeasureRangeList();
            _cmbReceivedBinning.DataSource = GetReceivedBiginning();
            _cmbCompressX.DataSource = GetCompressX();

            _cmbMeasureX.SelectedValue = Define.MEASURE_RANGE_FULL;
            _cmbReceivedBinning.SelectedValue = Define.RECEIVED_BINNING_OFF;
            _cmbCompressX.SelectedValue = Define.COMPRESS_X_OFF;

            _cbxSelectProgram.SelectedIndex = 2;

            // For use in profile export control
            //_txtboxProfileFilePath.Text = Directory.GetCurrentDirectory() + @"\" + Define.DEFAULT_PROFILE_FILE_NAME;
            //_txtboxProfileFilePath.SelectionStart = _txtboxProfileFilePath.Text.Length;
        }
Example #31
0
        public void RequestData()
        {
            _form.CaptionWaitFor("Transfering Data");

            while (_traces.Any())
            {
                _traces.Clear();
            }

            while (_traceBuffer.Any())
            {
                _traceBuffer.Clear();
            }

            var commandBinary = new SendCommand((int)Command.RequestData);

            // Send command
            _cmdMessenger.SendCommand(commandBinary);
        }
Example #32
0
        /// <summary>
        /// "GetStorageData" button clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetStorageData_Click(object sender, EventArgs e)
        {
            _sendCommand = SendCommand.GetStorageData;

            using (GetStorageDataForm getStorageData = new GetStorageDataForm())
            {
                if (DialogResult.OK == getStorageData.ShowDialog())
                {
                    _measureDatas.Clear();
                    LJV7IF_GET_STORAGE_REQ req = getStorageData.Req;
                    // @Point
                    // # dwReadArea is the target surface to read.
                    //    The target surface to read indicates where in the internal memory usage area to read.
                    // # The method to use in specifying dwReadArea varies depending on how internal memory is allocated.
                    //   * Double buffer
                    //      0 indicates the active surface, 1 indicates surface A, and 2 indicates surface B.
                    //   * Entire area (overwrite)
                    //      Fixed to 1
                    //   * Entire area (do not overwrite)
                    //      After a setting modification, data is saved in surfaces 1, 2, 3, and so on in order, and 0 is set as the active surface.
                    // # For details, see "9.2.9.2 Internal memory."

                    LJV7IF_STORAGE_INFO storageInfo = new LJV7IF_STORAGE_INFO();
                    LJV7IF_GET_STORAGE_RSP rsp = new LJV7IF_GET_STORAGE_RSP();
                    uint oneDataSize = (uint)(Marshal.SizeOf(typeof(uint)) + (uint)Utility.GetByteSize(Utility.TypeOfStruct.MEASURE_DATA) * (uint)NativeMethods.MeasurementDataCount);
                    uint allDataSize = Math.Min(Define.READ_DATA_SIZE, oneDataSize * getStorageData.Req.dwDataCnt);
                    byte[] receiveData = new byte[allDataSize];
                    using (PinnedObject pin = new PinnedObject(receiveData))
                    {
                        int rc = NativeMethods.LJV7IF_GetStorageData(_currentDeviceId, ref req, ref storageInfo, ref rsp, pin.Pointer, allDataSize);
                        AddLogResult(rc, Resources.SID_GET_STORAGE_DATA);
                        // @Point
                        // # Terminology
                        //  * Base time … time expressed with 32 bits (<- the time when the setting was changed)
                        //  * Accumulated date and time	 … counter value that indicates the elapsed time, in units of 10 ms, from the base time
                        // # The accumulated date and time are stored in the accumulated data.
                        // # The accumulated time of read data is calculated as shown below.
                        //   Accumulated time = "base time (stBaseTime of LJV7IF_GET_STORAGE_RSP)" + "accumulated date and time × 10 ms"

                        if (rc == (int)Rc.Ok)
                        {
                            // Temporarily retain the get data.
                            int byteSize = MeasureData.GetByteSize();
                            for (int i = 0; i < (int)rsp.dwDataCnt; i++)
                            {
                                _measureDatas.Add(new MeasureData(receiveData, byteSize * i));
                            }

                            // Response data display
                            AddLog(Utility.ConvertToLogString(storageInfo).ToString());
                            AddLog(Utility.ConvertToLogString(rsp).ToString());
                        }
                    }
                }
            }
        }
Example #33
0
 /// <summary> Queue the send command. </summary>
 /// <param name="sendCommand"> The command to sent. </param>
 public void QueueCommand(SendCommand sendCommand)
 {            
     QueueCommand(new CommandStrategy(sendCommand));
 }
Example #34
0
 /// <summary> Sends a command. Note that the command is put at the front of the queue </summary>
 /// <param name="sendCommand"> The command to sent. </param>
 public void SendCommand(SendCommand sendCommand)
 {
     // Add command to front of queue
     QueueCommand(new TopCommandStrategy(sendCommand));
 }
Example #35
0
        /// <summary>
        /// "StopStorage" button clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStopStorage_Click(object sender, EventArgs e)
        {
            _sendCommand = SendCommand.StopStorage;

            int rc = NativeMethods.LJV7IF_StopStorage(_currentDeviceId);
            AddLogResult(rc, Resources.SID_STOP_STORAGE);
        }
Example #36
0
        /// <summary>
        /// "GetProfileAdvance" button clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetProfileAdvance_Click(object sender, EventArgs e)
        {
            _sendCommand = SendCommand.GetProfileAdvance;
            _deviceData[_currentDeviceId].ProfileData.Clear();
            _deviceData[_currentDeviceId].MeasureData.Clear();
            _measureDatas.Clear();

            // Set the command function
            LJV7IF_PROFILE_INFO profileInfo = new LJV7IF_PROFILE_INFO();
            uint dataSize = GetOneProfileDataSize();
            int[] profileData = new int[dataSize / Marshal.SizeOf(typeof(int))];
            LJV7IF_MEASURE_DATA[] measureData = new LJV7IF_MEASURE_DATA[NativeMethods.MeasurementDataCount];

            using (PinnedObject pin = new PinnedObject(profileData))
            {
                // Send the command
                int rc = NativeMethods.LJV7IF_GetProfileAdvance(_currentDeviceId, ref profileInfo, pin.Pointer, dataSize, measureData);

                // Result output
                AddLogResult(rc, Resources.SID_GET_PROFILE_ADVANCE);
                if (rc == (int)Rc.Ok)
                {
                    // Response data display
                    AddLog(Utility.ConvertToLogString(profileInfo).ToString());

                    _measureDatas.Add(new MeasureData(0, measureData));
                    AnalyzeProfileData(1, ref profileInfo, profileData);
                    for (int i = 0; i < NativeMethods.MeasurementDataCount; i++)
                    {
                        AddLog(string.Format("  OUT{0:00}: {1}", (i + 1), Utility.ConvertToLogString(measureData[i]).ToString()));
                    }
                }
            }
        }
        /// <summary>
        /// Send data immediately to the serial port.
        /// </summary>
        /// <param name="sendCommand"></param>
        /// <returns></returns>
        private IEnumerator<ITask> CommSendImmediateHandler(SendCommand sendCommand)
        {
           
            Fault fault = null;
            if (_commState.SerialPort == null
                || !_commState.SerialPort.IsOpen)
            {
                fault = Fault.FromException(new NullReferenceException("The Lego Serial Port is disconnected."));
            }
            else if (sendCommand == null
                || sendCommand.Body == null
                || sendCommand.Body.LegoCommand == null
                || sendCommand.Body.LegoCommand.CommandData == null
                || sendCommand.Body.LegoCommand.CommandData.Length == 0)
            {
                fault = Fault.FromException(new NullReferenceException("Invalid Lego Command"));
            }

            if (fault != null)
            {
                if (sendCommand.Body.InternalResponsePort != null)
                    sendCommand.Body.InternalResponsePort.Post(fault);
                else if (sendCommand.ResponsePort != null)
                    sendCommand.ResponsePort.Post(fault);

                yield break;
            }
            byte[] data = sendCommand.Body.LegoCommand.CommandData;
            LogInfo("Sending Data -------------------------------------");
            for (int i = 0; i < data.Length; i++)
                LogInfo(data[i].ToString(CultureInfo.InvariantCulture));
            int packetLength = data.Length;

            try
            {
                if ((sendCommand.Body.LegoCommand.RequireResponse)
                    && (sendCommand.Body.Stopwatch != null))
                {
                    sendCommand.Body.Stopwatch.Start();
                }

                if (_state.ConnectOverBluetooth)
                {
                    // Add the bluetooth packet length 
                    buffer[0] = (byte)(packetLength % 256);
                    buffer[1] = (byte)(packetLength / 256);

                    // Write the bluetooth header
                    _commState.SerialPort.Write(buffer, 0, 2);
                }

                _commState.SerialPort.Write(data, 0, packetLength);

                if (sendCommand.Body.LegoCommand.RequireResponse)
                {
                    // calculate the minimum expected response time for this command.
                    sendCommand.Body.MinExpectedTimeSpan = CalcMinWaitTimeSpan(sendCommand.Body.LegoCommand.LegoCommandCode);
                    _commState.PendingRequests.Push(sendCommand.Body);
                    if (_commState.PendingRequests.Count == 1)
                    {
                        //Debugger.Break();
                        _commGetResponsePort.Post(GetResponse.Instance);
                    }
                        

                    // Signal intermediate completion
                    if (sendCommand.Body.InternalResponsePort != null)
                        sendCommand.Body.InternalResponsePort.Post(EmptyValue.SharedInstance);
                }
                else
                {
                    // Send an empty success response.
                    LegoResponse response = sendCommand.Body.LegoCommand.GetResponse(null);
                    sendCommand.ResponsePort.Post(response);
                }
            }
            catch (Exception ex)
            {
                if (ex is System.TimeoutException)
                {
                    // A write timeout means the serial port is no longer connected.
                    _state.Connected = false;
                    SendNotification<ConnectionUpdate>(_subMgrPort, new ConnectionUpdate(_state.Connected));
                }

                fault = Fault.FromException(ex);
                if (sendCommand.Body.LegoCommand.RequireResponse)
                {
                    if (sendCommand.Body.InternalResponsePort != null)
                        sendCommand.Body.InternalResponsePort.Post(fault);
                }
                else // respond directly to the source
                {
                    sendCommand.ResponsePort.Post(fault);
                }
            }
        }
        public virtual IEnumerator<ITask> SendCommandHandler(SendCommand sendCommand)
        {


            if (buffer == null || _commState.SerialPort == null || !_commState.SerialPort.IsOpen)
            {
                sendCommand.ResponsePort.Post(Fault.FromException(new InvalidOperationException("Not Connected")));
                yield break;
            }
            if (sendCommand.Body == null || sendCommand.Body.LegoCommand == null)
            {
                sendCommand.ResponsePort.Post(Fault.FromException(new InvalidOperationException("Invalid LEGO Command")));
                yield break;
            }

            // Dispatch again to one of three different ports:
            // If no response is required, send the command immediately
            // Otherwise queue into a low or high priority queue to
            // be handled one command/response at a time.
            if (!sendCommand.Body.LegoCommand.RequireResponse)
                _commSendImmediatePort.Post(sendCommand);
            else if (sendCommand.Body.PriorityRequest)
                _legoPriorityRequestResponsePort.Post(sendCommand);
            else
                _legoRequestResponsePort.Post(sendCommand);

            yield break;
        }
Example #39
0
        /// <summary>
        /// "PreStartHighSpeedDataCommunication" button clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPreStartHighSpeedDataCommunication_Click(object sender, EventArgs e)
        {
            _sendCommand = SendCommand.PreStartHighSpeedDataCommunication;

            using (PreStartHighSpeedForm preStartHighSpeedForm = new PreStartHighSpeedForm())
            {
                if (DialogResult.OK == preStartHighSpeedForm.ShowDialog())
                {
                    LJV7IF_HIGH_SPEED_PRE_START_REQ req = preStartHighSpeedForm.Req;
                    // @Point
                    // # SendPos is used to specify which profile to start sending data from during high-speed communication.
                    // # When "Overwrite" is specified for the operation when memory full and
                    //   "0: From previous send complete position" is specified for the send start position,
                    //    if the LJ-V continues to accumulate profiles, the LJ-V memory will become full,
                    //    and the profile at the previous send complete position will be overwritten with a new profile.
                    //    In this situation, because the profile at the previous send complete position is not saved, an error will occur.

                    LJV7IF_PROFILE_INFO profileInfo = new LJV7IF_PROFILE_INFO();

                    int rc = NativeMethods.LJV7IF_PreStartHighSpeedDataCommunication(_currentDeviceId, ref req, ref profileInfo);
                    AddLogResult(rc, Resources.SID_PRE_START_HIGH_SPEED_DATA_COMMUNICATION);
                    if (rc == (int)Rc.Ok)
                    {
                        // Response data display
                        AddLog(Utility.ConvertToLogString(profileInfo).ToString());
                        _profileInfo[_currentDeviceId] = profileInfo;
                    }
                }
            }
        }
Example #40
0
        /// <summary>
        /// "GetBatchProfile" button clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetBatchProfile_Click(object sender, EventArgs e)
        {
            _sendCommand = SendCommand.GetBatchProfile;

            using (GetBatchProfileForm getBatchProfileForm = new GetBatchProfileForm())
            {
                if (DialogResult.OK == getBatchProfileForm.ShowDialog())
                {
                    _deviceData[_currentDeviceId].ProfileData.Clear();
                    _deviceData[_currentDeviceId].MeasureData.Clear();
                    // Set the command function
                    LJV7IF_GET_BATCH_PROFILE_REQ req = getBatchProfileForm.Req;
                    LJV7IF_GET_BATCH_PROFILE_RSP rsp = new LJV7IF_GET_BATCH_PROFILE_RSP();
                    LJV7IF_PROFILE_INFO profileInfo = new LJV7IF_PROFILE_INFO();
                    uint oneDataSize = GetOneProfileDataSize();
                    uint allDataSize = oneDataSize * getBatchProfileForm.Req.byGetProfCnt;
                    int[] profileData = new int[allDataSize / Marshal.SizeOf(typeof(int))];

                    using (PinnedObject pin = new PinnedObject(profileData))
                    {
                        // Send the command
                        int rc = NativeMethods.LJV7IF_GetBatchProfile(_currentDeviceId, ref req, ref rsp, ref profileInfo, pin.Pointer, allDataSize);
                        // @Point
                        // # When reading all the profiles from a single batch, the specified number of profiles may not be read.
                        // # To read the remaining profiles after the first set of profiles have been read,
                        //    set the specification method (byPosMode)to 0x02, specify the batch number (dwGetBatchNo),
                        //    and then set the number to start reading profiles from (dwGetProfNo) and the number of profiles to read (byGetProfCnt) to values
                        //    that specify a range of profiles that have not been read to read the profiles in order.
                        // # For the basic code, see "btnGetBatchProfileEx_Click."

                        // Result output
                        AddLogResult(rc, Resources.SID_GET_BATCH_PROFILE);
                        if (rc == (int)Rc.Ok)
                        {
                            // Response data display
                            AddLog(Utility.ConvertToLogString(rsp).ToString());
                            AddLog(Utility.ConvertToLogString(profileInfo).ToString());

                            AnalyzeProfileData((int)rsp.byGetProfCnt, ref profileInfo, profileData);

                            // Profile export
                            if (DataExporter.ExportOneProfile(_deviceData[_currentDeviceId].ProfileData.ToArray(), 0, _txtboxProfileFilePath.Text))
                            {
                                AddLog(@"###Saved!!");
                            }

                        }
                    }
                }
            }
        }
Example #41
0
        /// <summary>
        /// "GetBatchProfileAdvance" button clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetBatchProfileAdvance_Click(object sender, EventArgs e)
        {
            _sendCommand = SendCommand.GetBatchProfileAdvance;

            using (GetBatchprofileAdvanceForm getBatchprofileAdvanceForm = new GetBatchprofileAdvanceForm())
            {
                if (DialogResult.OK == getBatchprofileAdvanceForm.ShowDialog())
                {
                    _deviceData[_currentDeviceId].ProfileData.Clear();
                    _deviceData[_currentDeviceId].MeasureData.Clear();
                    _measureDatas.Clear();

                    // Set the command function
                    LJV7IF_GET_BATCH_PROFILE_ADVANCE_REQ req = getBatchprofileAdvanceForm.Req;
                    LJV7IF_GET_BATCH_PROFILE_ADVANCE_RSP rsp = new LJV7IF_GET_BATCH_PROFILE_ADVANCE_RSP();
                    LJV7IF_PROFILE_INFO profileInfo = new LJV7IF_PROFILE_INFO();
                    uint oneDataSize = GetOneProfileDataSize() + (uint)Utility.GetByteSize(Utility.TypeOfStruct.MEASURE_DATA) * (uint)NativeMethods.MeasurementDataCount;
                    uint allDataSize = oneDataSize * getBatchprofileAdvanceForm.Req.byGetProfCnt;
                    int[] profileData = new int[allDataSize / Marshal.SizeOf(typeof(int))];
                    LJV7IF_MEASURE_DATA[] measureData = new LJV7IF_MEASURE_DATA[NativeMethods.MeasurementDataCount];
                    LJV7IF_MEASURE_DATA[] batchMeasureData = new LJV7IF_MEASURE_DATA[NativeMethods.MeasurementDataCount];

                    using (PinnedObject pin = new PinnedObject(profileData))
                    {
                        // Send the command
                        int rc = NativeMethods.LJV7IF_GetBatchProfileAdvance(_currentDeviceId, ref req, ref rsp,
                            ref profileInfo, pin.Pointer, allDataSize, batchMeasureData, measureData);
                        // @Point
                        // # When reading all the profiles from a single batch, the specified number of profiles may not be read.
                        // # To read the remaining profiles after the first set of profiles have been read,
                        //    set the specification method (byPosMode)to 0x02, specify the batch number (dwGetBatchNo),
                        //    and then set the number to start reading profiles from (dwGetProfNo) and the number of profiles to read (byGetProfCnt) to values
                        //    that specify a range of profiles that have not been read to read the profiles in order.
                        // # For the basic code, see "btnGetBatchProfileEx_Click."

                        // Result output
                        AddLogResult(rc, Resources.SID_GET_BATCH_PROFILE_ADVANCE);
                        if (rc == (int)Rc.Ok)
                        {
                            _measureDatas.Add(new MeasureData(0, measureData));
                            AddLog(Utility.ConvertToLogString(rsp).ToString());
                            AddLog(Utility.ConvertToLogString(profileInfo).ToString());
                            for (int i = 0; i < NativeMethods.MeasurementDataCount; i++)
                            {
                                AddLog(string.Format("  OUT{0:00}: {1}", (i + 1), Utility.ConvertToLogString(measureData[i]).ToString()));
                            }

                            AnalyzeBatchData((int)rsp.byGetProfCnt, ref profileInfo, false, profileData, 0);

                            // Profile export
                            if (DataExporter.ExportOneProfile(_deviceData[_currentDeviceId].ProfileData.ToArray(), 0, _txtboxProfileFilePath.Text))
                            {
                                AddLog(@"###Saved!!");
                            }
                        }
                    }
                }
            }
        }
Example #42
0
        /// <summary>
        /// "ChangeActiveProgram" button clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnChangeActiveProgram_Click(object sender, EventArgs e)
        {
            _sendCommand = SendCommand.ChangeActiveProgram;

            using (DepthProgramSelectForm depthProgramSelectForm = new DepthProgramSelectForm(false, true))
            {
                if (DialogResult.OK == depthProgramSelectForm.ShowDialog())
                {
                    int rc = NativeMethods.LJV7IF_ChangeActiveProgram(_currentDeviceId, depthProgramSelectForm.Target);
                    AddLogResult(rc, Resources.SID_CHANGE_ACTIVE_PROGRAM);
                }
            }
        }
Example #43
0
        /// <summary>
        /// "AutoZero" button clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAutoZero_Click(object sender, EventArgs e)
        {
            _sendCommand = SendCommand.AutoZero;

            using (OutSelectForm autoZeroForm = new OutSelectForm(true))
            {
                if (DialogResult.OK == autoZeroForm.ShowDialog())
                {
                    int rc = NativeMethods.LJV7IF_AutoZero(_currentDeviceId, autoZeroForm.OnOff, autoZeroForm.Out);
                    AddLogResult(rc, Resources.SID_AUTO_ZERO);
                }
            }
        }
Example #44
0
        /// <summary>
        /// "Trigger" button clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTrigger_Click(object sender, EventArgs e)
        {
            _sendCommand = SendCommand.Trigger;

            int rc = NativeMethods.LJV7IF_Trigger(_currentDeviceId);
            AddLogResult(rc, Resources.SID_TRIGGER);
        }
Example #45
0
        /// <summary>
        /// "GetStorageBatchProfile" button clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetStorageBatchProfile_Click(object sender, EventArgs e)
        {
            _sendCommand = SendCommand.GetStorageBatchProfile;

            using (GetStorageBatchProfileForm getStorageBatchProfileForm = new GetStorageBatchProfileForm())
            {
                if (DialogResult.OK == getStorageBatchProfileForm.ShowDialog())
                {
                    _deviceData[_currentDeviceId].ProfileData.Clear();
                    _deviceData[_currentDeviceId].MeasureData.Clear();
                    _measureDatas.Clear();
                    // Set the function data
                    LJV7IF_GET_BATCH_PROFILE_STORAGE_REQ req = getStorageBatchProfileForm.Req;
                    LJV7IF_STORAGE_INFO storageInfo = new LJV7IF_STORAGE_INFO();
                    LJV7IF_GET_BATCH_PROFILE_STORAGE_RSP rsp = new LJV7IF_GET_BATCH_PROFILE_STORAGE_RSP();
                    LJV7IF_PROFILE_INFO profileInfo = new LJV7IF_PROFILE_INFO();
                    uint oneDataSize = GetOneProfileDataSize() + (uint)(Utility.GetByteSize(Utility.TypeOfStruct.MEASURE_DATA) * (uint)NativeMethods.MeasurementDataCount);
                    uint allDataSize = oneDataSize * getStorageBatchProfileForm.Req.byGetProfCnt;
                    LJV7IF_MEASURE_DATA[] measureData = new LJV7IF_MEASURE_DATA[NativeMethods.MeasurementDataCount];
                    int[] profileData = new int[allDataSize / Marshal.SizeOf(typeof(int))];
                    uint offsetTime = 0;

                    using (PinnedObject pin = new PinnedObject(profileData))
                    {
                        // Send the command
                        int rc = NativeMethods.LJV7IF_GetStorageBatchProfile(_currentDeviceId, ref req, ref storageInfo,
                            ref rsp, ref profileInfo, pin.Pointer, allDataSize, ref offsetTime, measureData);
                        // @Point
                        // # Terminology
                        //  * Base time … time expressed with 32 bits (<- the time when the setting was changed)
                        //  * Accumulated date and time	 … counter value that indicates the elapsed time, in units of 10 ms, from the base time
                        // # The accumulated date and time are stored in the accumulated data.
                        // # The accumulated time of read data is calculated as shown below.
                        //   Accumulated time = "base time (stBaseTime of LJV7IF_GET_STORAGE_RSP)" + "accumulated date and time × 10 ms"

                        // @Point
                        // # When reading all the profiles from a single batch, the specified number of profiles may not be read.
                        // # To read the remaining profiles after the first set of profiles have been read,
                        //   specify the batch number (dwGetBatchNo), and then set the number to start reading profiles
                        //   from (dwGetTopProfNo) and the number of profiles to read (byGetProfCnt) to values
                        //   that specify a range of profiles that have not been read to read the profiles in order.
                        // # For the basic code, see "btnGetBatchProfileEx_Click."

                        // Result output
                        AddLogResult(rc, Resources.SID_GET_STORAGE_BATCH_PROFILE);
                        if (rc == (int)Rc.Ok)
                        {
                            AnalyzeBatchData((int)rsp.byGetProfCnt, ref profileInfo, false, profileData, 0);

                            _measureDatas.Add(new MeasureData(offsetTime, measureData));
                            // Response data display
                            AddLog(Utility.ConvertToLogString(storageInfo).ToString());
                            AddLog(Utility.ConvertToLogString(rsp).ToString());
                            AddLog(Utility.ConvertToLogString(profileInfo).ToString());
                            AddLog(string.Format(@"offsetTime	:{0}", offsetTime));
                        }
                    }
                }
            }
        }
Example #46
0
        /// <summary>
        /// "GetProfile" button clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetProfile_Click(object sender, EventArgs e)
        {
            _sendCommand = SendCommand.GetProfile;

            using (ProfileForm profileForm = new ProfileForm())
            {
                if (DialogResult.OK == profileForm.ShowDialog())
                {
                    _deviceData[_currentDeviceId].ProfileData.Clear();
                    _deviceData[_currentDeviceId].MeasureData.Clear();
                    LJV7IF_GET_PROFILE_REQ req = profileForm.Req;
                    LJV7IF_GET_PROFILE_RSP rsp = new LJV7IF_GET_PROFILE_RSP();
                    LJV7IF_PROFILE_INFO profileInfo = new LJV7IF_PROFILE_INFO();
                    uint oneProfDataBuffSize = GetOneProfileDataSize();
                    uint allProfDataBuffSize = oneProfDataBuffSize * req.byGetProfCnt;
                    int[] profileData = new int[allProfDataBuffSize / Marshal.SizeOf(typeof(int))];

                    using (PinnedObject pin = new PinnedObject(profileData))
                    {
                        int rc = NativeMethods.LJV7IF_GetProfile(_currentDeviceId, ref req, ref rsp, ref profileInfo, pin.Pointer, allProfDataBuffSize);
                        AddLogResult(rc, Resources.SID_GET_PROFILE);
                        if (rc == (int)Rc.Ok)
                        {
                            // Response data display
                            AddLog(Utility.ConvertToLogString(rsp).ToString());
                            AddLog(Utility.ConvertToLogString(profileInfo).ToString());

                            AnalyzeProfileData((int)rsp.byGetProfCnt, ref profileInfo, profileData);

                            // Profile export
                            if (DataExporter.ExportOneProfile(_deviceData[_currentDeviceId].ProfileData.ToArray(), 0, _txtboxProfileFilePath.Text))
                            {
                                AddLog(@"###Saved!!");
                            }
                        }
                    }
                }
            }
        }
Example #47
0
        /// <summary>
        /// "HighSpeedDataUsbCommunicationInitalize" button clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnHighSpeedDataUsbCommunicationInitalize_Click(object sender, EventArgs e)
        {
            _sendCommand = SendCommand.HighSpeedDataUsbCommunicationInitalize;

            using (HighSpeedInitalizeForm highSpeedInitalizeForm = new HighSpeedInitalizeForm(false))
            {
                if (DialogResult.OK == highSpeedInitalizeForm.ShowDialog())
                {
                    _deviceData[_currentDeviceId].ProfileData.Clear();  // Clear the retained profile data.
                    _deviceData[_currentDeviceId].MeasureData.Clear();

                    int rc = NativeMethods.LJV7IF_HighSpeedDataUsbCommunicationInitalize(_currentDeviceId,
                        (_chkOnlyProfileCount.Checked ? _callbackOnlyCount : _callback),
                        highSpeedInitalizeForm.ProfileCnt, (uint)_currentDeviceId);
                    // @Point
                    // # When the frequency of calls is low, the callback function may not be called once per specified number of profiles.
                    // # The callback function is called when both of the following conditions are met.
                    //   * There is one packet of received data.
                    //   * The specified number of profiles have been received by the time the call frequency has been met.

                    AddLogResult(rc, Resources.SID_HIGH_SPEED_DATA_USB_COMMUNICATION_INITALIZE);

                    if (rc == (int)Rc.Ok) _deviceData[_currentDeviceId].Status = DeviceStatus.UsbFast;
                    _deviceStatusLabels[_currentDeviceId].Text = _deviceData[_currentDeviceId].GetStatusString();
                }
            }
        }
        /// <summary>
        /// Handle Requests with Responses
        /// </summary>
        /// <param name="sendCommand"></param>
        /// <returns></returns>
        private IEnumerator<ITask> RequestResponseHandler(SendCommand sendCommand)
        {
            // Keep track of consecutive priority requests.
            if (sendCommand.Body.PriorityRequest)
                _commState.ConsecutivePriorityRequests++;
            else
                _commState.ConsecutivePriorityRequests = 0;

            try
            {
                Fault faultResponse = null;

                // Process Priority Request

                // Set up an intermediate response port.
                sendCommand.Body.InternalResponsePort = new PortSet<EmptyValue, LegoResponse, Fault>();
                sendCommand.Body.Stopwatch = GetStopwatch();

                // Send the command to the serial port
                _commSendImmediatePort.Post(sendCommand);

                // Wait for the data to be sent
                yield return Arbiter.Choice(
                    Arbiter.Receive<EmptyValue>(false, sendCommand.Body.InternalResponsePort, EmptyHandler<EmptyValue>),
                    Arbiter.Receive<Fault>(false, sendCommand.Body.InternalResponsePort,
                    delegate(Fault fault)
                    {
                        faultResponse = fault;
                    }));

                // early exit
                if (faultResponse != null)
                {
                    RetireStopwatch(ref sendCommand.Body.Stopwatch);
                    sendCommand.ResponsePort.Post(faultResponse);
                    yield break;
                }

                // wait for the response
                yield return Arbiter.Choice(
                    Arbiter.Receive<LegoResponse>(false, sendCommand.Body.InternalResponsePort,
                        delegate(LegoResponse response)
                        {
                            //////Debugger.Break();
                            sendCommand.ResponsePort.Post(response);
                        }),
                    Arbiter.Receive<Fault>(false, sendCommand.Body.InternalResponsePort,
                        delegate(Fault fault)
                        {
                            sendCommand.ResponsePort.Post(fault);
                        }));

                RetireStopwatch(ref sendCommand.Body.Stopwatch);

                yield break;

            }
            finally
            {
                // Decide which request queue is next.
                ActivateNextRequest();
            }
        }
Example #49
0
        /// <summary>
        /// "GetStorageStatus" button clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetStorageStatus_Click(object sender, EventArgs e)
        {
            _sendCommand = SendCommand.GetStorageStatus;

            using (GetStorageStatusForm getStorageStatusForm = new GetStorageStatusForm())
            {
                if (DialogResult.OK == getStorageStatusForm.ShowDialog())
                {
                    LJV7IF_GET_STRAGE_STATUS_REQ req = getStorageStatusForm.Req;
                    // @Point
                    // # dwReadArea is the target surface to read.
                    //   The target surface to read indicates where in the internal memory usage area to read.
                    // # The method to use in specifying dwReadArea varies depending on how internal memory is allocated.
                    //   * Double buffer
                    //      0 indicates the active surface, 1 indicates surface A, and 2 indicates surface B.
                    //   * Entire area (overwrite)
                    //      Fixed to 1
                    //   * Entire area (do not overwrite)
                    //      After a setting modification, data is saved in surfaces 1, 2, 3, and so on in order, and 0 is set as the active surface.
                    // # For details, see "9.2.9.2 Internal memory."

                    LJV7IF_GET_STRAGE_STATUS_RSP rsp = new LJV7IF_GET_STRAGE_STATUS_RSP();
                    LJV7IF_STORAGE_INFO storageInfo = new LJV7IF_STORAGE_INFO();

                    int rc = NativeMethods.LJV7IF_GetStorageStatus(_currentDeviceId, ref req, ref rsp, ref storageInfo);
                    // @Point
                    // # Terminology
                    //  * Base time … time expressed with 32 bits (<- the time when the setting was changed)
                    //  * Accumulated date and time	 … counter value that indicates the elapsed time, in units of 10 ms, from the base time
                    // # The accumulated date and time are stored in the accumulated data.
                    // # The accumulated time of read data is calculated as shown below.
                    //   Accumulated time = "base time (stBaseTime of LJV7IF_GET_STORAGE_RSP)" + "accumulated date and time × 10 ms"

                    AddLogResult(rc, Resources.SID_GET_STORAGE_STATUS);
                    if (rc == (int)Rc.Ok)
                    {
                        // Response data display
                        AddLog(Utility.ConvertToLogString(rsp).ToString());
                        AddLog(Utility.ConvertToLogString(storageInfo).ToString());
                    }
                }
            }
        }
Example #50
0
        /// <summary>
        /// "GetMeasurementValue" button clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetMeasurementValue_Click(object sender, EventArgs e)
        {
            _sendCommand = SendCommand.GetMeasurementValue;

            LJV7IF_MEASURE_DATA[] measureData = new LJV7IF_MEASURE_DATA[NativeMethods.MeasurementDataCount];
            int rc = NativeMethods.LJV7IF_GetMeasurementValue(_currentDeviceId, measureData);
            AddLogResult(rc, Resources.SID_GET_MEASUREMENT_VALUE);
            if (rc == (int)Rc.Ok)
            {
                _measureDatas.Clear();
                _measureDatas.Add(new MeasureData(0, measureData));

                for (int i = 0; i < NativeMethods.MeasurementDataCount; i++)
                {
                    AddLog(string.Format("  OUT{0:00}: {1}", (i + 1), Utility.ConvertToLogString(measureData[i]).ToString()));
                }
            }
        }
Example #51
0
        /// <summary>
        /// "StartHighSpeedDataCommunication" button clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStartHighSpeedDataCommunication_Click(object sender, EventArgs e)
        {
            _sendCommand = SendCommand.StartHighSpeedDataCommunication;

            ThreadSafeBuffer.ClearBuffer(_currentDeviceId);
            _receivedProfileCountLabels[_currentDeviceId].Text = "0";
            int rc = NativeMethods.LJV7IF_StartHighSpeedDataCommunication(_currentDeviceId);
            // @Point
            //  If the LJ-V does not measure the profile for 30 seconds from the start of transmission,
            //  "0x00000008" is stored in dwNotify of the callback function.

            AddLogResult(rc, Resources.SID_START_HIGH_SPEED_DATA_COMMUNICATION);
        }
Example #52
0
        /// <summary>
        /// "GetStorageProfile" button clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetStorageProfile_Click(object sender, EventArgs e)
        {
            _sendCommand = SendCommand.GetStorageProfile;

            using (GetStorageDataForm getStorageData = new GetStorageDataForm())
            {
                if (DialogResult.OK == getStorageData.ShowDialog())
                {
                    _deviceData[_currentDeviceId].ProfileData.Clear();
                    _deviceData[_currentDeviceId].MeasureData.Clear();
                    _measureDatas.Clear();
                    LJV7IF_GET_STORAGE_REQ req = getStorageData.Req;
                    // @Point
                    // # dwReadArea is the target surface to read.
                    //   The target surface to read indicates where in the internal memory usage area to read.
                    // # The method to use in specifying dwReadArea varies depending on how internal memory is allocated.
                    //   * Double buffer
                    //      0 indicates the active surface, 1 indicates surface A, and 2 indicates surface B.
                    //   * Entire area (overwrite)
                    //      Fixed to 1
                    //   * Entire area (do not overwrite)
                    //      After a setting modification, data is saved in surfaces 1, 2, 3, and so on in order, and 0 is set as the active surface.
                    // # For details, see "9.2.9.2 Internal memory."

                    LJV7IF_STORAGE_INFO storageInfo = new LJV7IF_STORAGE_INFO();
                    LJV7IF_GET_STORAGE_RSP rsp = new LJV7IF_GET_STORAGE_RSP();
                    LJV7IF_PROFILE_INFO profileInfo = new LJV7IF_PROFILE_INFO();

                    uint oneDataSize = (uint)(Marshal.SizeOf(typeof(uint)) + (uint)Utility.GetByteSize(Utility.TypeOfStruct.MEASURE_DATA)
                        * (uint)NativeMethods.MeasurementDataCount * 2 + GetOneProfileDataSize());
                    uint allDataSize = Math.Min(Define.READ_DATA_SIZE, oneDataSize * getStorageData.Req.dwDataCnt);
                    byte[] receiveData = new byte[allDataSize];
                    using (PinnedObject pin = new PinnedObject(receiveData))
                    {
                        int rc = NativeMethods.LJV7IF_GetStorageProfile(_currentDeviceId, ref req, ref storageInfo, ref rsp, ref profileInfo, pin.Pointer, allDataSize);
                        // @Point
                        // # Terminology
                        //  * Base time … time expressed with 32 bits (<- the time when the setting was changed)
                        //  * Accumulated date and time	 … counter value that indicates the elapsed time, in units of 10 ms, from the base time
                        // # The accumulated date and time are stored in the accumulated data.
                        // # The accumulated time of read data is calculated as shown below.
                        //   Accumulated time = "base time (stBaseTime of LJV7IF_GET_STORAGE_RSP)" + "accumulated date and time × 10 ms"

                        // @Point
                        // # When reading multiple profiles, the specified number of profiles may not be read.
                        // # To read the remaining profiles after the first set of profiles have been read,
                        //   set the number to start reading profiles from (dwStartNo) and the number of profiles to read (byDataCnt)
                        //   to values that specify a range of profiles that have not been read to read the profiles in order.
                        // # For the basic code, see "btnGetBatchProfileEx_Click."

                        AddLogResult(rc, Resources.SID_GET_STORAGE_PROFILE);
                        if (rc == (int)Rc.Ok)
                        {
                            // Temporarily retain the get data.
                            int measureDataSize = MeasureData.GetByteSize();
                            int profileDataSize = ProfileData.CalculateDataSize(profileInfo) * Marshal.SizeOf(typeof(int));
                            int profileMeasureDataSize = Utility.GetByteSize(Utility.TypeOfStruct.MEASURE_DATA) * NativeMethods.MeasurementDataCount;
                            int byteSize = measureDataSize + profileDataSize + profileMeasureDataSize;
                            byte[] tempRecvieMeasureData = new byte[profileMeasureDataSize];

                            for (int i = 0; i < (int)rsp.dwDataCnt; i++)
                            {
                                _measureDatas.Add(new MeasureData(receiveData, byteSize * i));
                                _deviceData[_currentDeviceId].ProfileData.Add(new ProfileData(receiveData, (measureDataSize + byteSize * i), profileInfo));
                                Buffer.BlockCopy(receiveData, (measureDataSize + profileDataSize + byteSize * i), tempRecvieMeasureData, 0, profileMeasureDataSize);
                                _deviceData[_currentDeviceId].MeasureData.Add(new MeasureData(tempRecvieMeasureData));
                            }

                            // Response data display
                            AddLog(Utility.ConvertToLogString(storageInfo).ToString());
                            AddLog(Utility.ConvertToLogString(rsp).ToString());
                            AddLog(Utility.ConvertToLogString(profileInfo).ToString());
                        }
                    }
                }
            }
        }
Example #53
0
        /// <summary>
        /// "StartMeasure" button clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStartMeasure_Click(object sender, EventArgs e)
        {
            _sendCommand = SendCommand.StartMeasure;

            int rc = NativeMethods.LJV7IF_StartMeasure(_currentDeviceId);
            AddLogResult(rc, Resources.SID_START_MEASURE);
        }
Example #54
0
        /// <summary>
        /// "Reset" button clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReset_Click(object sender, EventArgs e)
        {
            _sendCommand = SendCommand.Reset;

            using (OutSelectForm resetForm = new OutSelectForm(false))
            {
                if (DialogResult.OK == resetForm.ShowDialog())
                {
                    int rc = NativeMethods.LJV7IF_Reset(_currentDeviceId, resetForm.Out);
                    AddLogResult(rc, Resources.SID_RESET);
                }
            }
        }
Example #55
0
        /// <summary>
        /// "RebootController" button clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRebootController_Click(object sender, EventArgs e)
        {
            _sendCommand = SendCommand.RebootController;

            int rc = NativeMethods.LJV7IF_RebootController(_currentDeviceId);
            AddLogResult(rc, Resources.SID_REBOOT_CONTROLLER);
        }