Simulink link by tcpip with C++ application - c++
I am tryng to build a link between my simulink model or just an m file and my C++ application but I'm having an issue. I don't really understand how matlab receives the data, and for simulink in which form should I send the data to the block? I would like to send coordinates like xyz to matlab and with matlab scatter3 the stream of coordinates in real time. Is it possible ?
Here is the C++ extract code : (sorry comments are in french)
/* Démarrage du listage (mode server) */
sock_err = listen(sock, 5);
printf("Listage du port %d...\n", PORT);
/* Si la socket fonctionne */
if(sock_err != SOCKET_ERROR)
{
/* Attente pendant laquelle le client se connecte */
printf("Patientez pendant que le client se connecte sur le port %d...\n", PORT);
csock = accept(sock, (SOCKADDR*)&csin, &recsize);
printf("Un client se connecte avec la socket %d de %s:%d\n", csock, inet_ntoa(csin.sin_addr), htons(csin.sin_port));
// double buff = 25;
mxArray *datasend;
datasend = mxCreateDoubleMatrix(1, 1, mxREAL);
mlfPrintmatrix(datasend);
sock_err = send(csock, T, 3*sizeof(double), 0);
if(sock_err != SOCKET_ERROR)
printf("Send : %s\n", buffer[0]);
//printf("send : [10 20 30]");
else
printf("Erreur de transmission\n");
/* Il ne faut pas oublier de fermer la connexion (fermée dans les deux sens) */
shutdown(csock, 2);
}
Simulink errors:
Error evaluating registered method 'Outputs' of M-S-Function 'stcpiprb' in 'trajectory2/TCP//IP Receive'. The specified amount of data was not returned within the Timeout period.
Please ensure that data is being sent to the specified port or specify a greater timeout value.
The specified amount of data was not returned within the Timeout period.
Please ensure that data is being sent to the specified port or specify a greater timeout value.
simulink model :
Model {
Name "trajectory2"
Version 7.4
MdlSubVersion 0
GraphicalInterface {
NumRootInports 0
NumRootOutports 0
ParameterArgumentNames ""
ComputedModelVersion "1.3"
NumModelReferences 0
NumTestPointedSignals 0
}
SavedCharacterEncoding "UTF-8"
SaveDefaultBlockParams on
ScopeRefreshTime 0.035000
OverrideScopeRefreshTime on
DisableAllScopes off
DataTypeOverride "UseLocalSettings"
MinMaxOverflowLogging "UseLocalSettings"
MinMaxOverflowArchiveMode "Overwrite"
MaxMDLFileLineLength 120
Created "Tue Feb 23 11:53:02 2010"
Creator "root"
UpdateHistory "UpdateHistoryNever"
ModifiedByFormat "%<Auto>"
LastModifiedBy "root"
ModifiedDateFormat "%<Auto>"
LastModifiedDate "Wed Feb 24 01:01:41 2010"
RTWModifiedTimeStamp 188862533
ModelVersionFormat "1.%<AutoIncrement:3>"
ConfigurationManager "None"
SampleTimeColors off
SampleTimeAnnotations off
LibraryLinkDisplay "none"
WideLines off
ShowLineDimensions off
ShowPortDataTypes off
ShowLoopsOnError on
IgnoreBidirectionalLines off
ShowStorageClass off
ShowTestPointIcons on
ShowSignalResolutionIcons on
ShowViewerIcons on
SortedOrder off
ExecutionContextIcon off
ShowLinearizationAnnotations on
BlockNameDataTip off
BlockParametersDataTip off
BlockDescriptionStringDataTip off
ToolBar on
StatusBar on
BrowserShowLibraryLinks off
BrowserLookUnderMasks off
SimulationMode "normal"
LinearizationMsg "none"
Profile off
ParamWorkspaceSource "MATLABWorkspace"
AccelSystemTargetFile "accel.tlc"
AccelTemplateMakefile "accel_default_tmf"
AccelMakeCommand "make_rtw"
TryForcingSFcnDF off
RecordCoverage off
CovPath "/"
CovSaveName "covdata"
CovMetricSettings "dw"
CovNameIncrementing off
CovHtmlReporting on
CovForceBlockReductionOff on
covSaveCumulativeToWorkspaceVar on
CovSaveSingleToWorkspaceVar on
CovCumulativeVarName "covCumulativeData"
CovCumulativeReport off
CovReportOnPause on
CovModelRefEnable "Off"
CovExternalEMLEnable off
ExtModeBatchMode off
ExtModeEnableFloating on
ExtModeTrigType "manual"
ExtModeTrigMode "normal"
ExtModeTrigPort "1"
ExtModeTrigElement "any"
ExtModeTrigDuration 1000
ExtModeTrigDurationFloating "auto"
ExtModeTrigHoldOff 0
ExtModeTrigDelay 0
ExtModeTrigDirection "rising"
ExtModeTrigLevel 0
ExtModeArchiveMode "off"
ExtModeAutoIncOneShot off
ExtModeIncDirWhenArm off
ExtModeAddSuffixToVar off
ExtModeWriteAllDataToWs off
ExtModeArmWhenConnect on
ExtModeSkipDownloadWhenConnect off
ExtModeLogAll on
ExtModeAutoUpdateStatusClock on
BufferReuse on
ShowModelReferenceBlockVersion off
ShowModelReferenceBlockIO off
Array {
Type "Handle"
Dimension 1
Simulink.ConfigSet {
$ObjectID 1
Version "1.6.0"
Array {
Type "Handle"
Dimension 9
Simulink.SolverCC {
$ObjectID 2
Version "1.6.0"
StartTime "0.0"
StopTime "10.0"
AbsTol "auto"
FixedStep "auto"
InitialStep "auto"
MaxNumMinSteps "-1"
MaxOrder 5
ZcThreshold "auto"
ConsecutiveZCsStepRelTol "10*128*eps"
MaxConsecutiveZCs "1000"
ExtrapolationOrder 4
NumberNewtonIterations 1
MaxStep "auto"
MinStep "auto"
MaxConsecutiveMinStep "1"
RelTol "1e-3"
SolverMode "Auto"
Solver "ode45"
SolverName "ode45"
ShapePreserveControl "DisableAll"
ZeroCrossControl "UseLocalSettings"
ZeroCrossAlgorithm "Nonadaptive"
AlgebraicLoopSolver "TrustRegion"
SolverResetMethod "Fast"
PositivePriorityOrder off
AutoInsertRateTranBlk off
SampleTimeConstraint "Unconstrained"
InsertRTBMode "Whenever possible"
}
Simulink.DataIOCC {
$ObjectID 3
Version "1.6.0"
Decimation "1"
ExternalInput "[t, u]"
FinalStateName "xFinal"
InitialState "xInitial"
LimitDataPoints on
MaxDataPoints "1000"
LoadExternalInput off
LoadInitialState off
SaveFinalState off
SaveCompleteFinalSimState off
SaveFormat "Array"
SaveOutput on
SaveState off
SignalLogging on
InspectSignalLogs off
SaveTime on
ReturnWorkspaceOutputs off
StateSaveName "xout"
TimeSaveName "tout"
OutputSaveName "yout"
SignalLoggingName "logsout"
OutputOption "RefineOutputTimes"
OutputTimes "[]"
ReturnWorkspaceOutputsName "out"
Refine "1"
}
Simulink.OptimizationCC {
$ObjectID 4
Version "1.6.0"
Array {
Type "Cell"
Dimension 7
Cell "BooleansAsBitfields"
Cell "PassReuseOutputArgsAs"
Cell "PassReuseOutputArgsThreshold"
Cell "ZeroExternalMemoryAtStartup"
Cell "ZeroInternalMemoryAtStartup"
Cell "OptimizeModelRefInitCode"
Cell "NoFixptDivByZeroProtection"
PropName "DisabledProps"
}
BlockReduction on
BooleanDataType on
ConditionallyExecuteInputs on
InlineParams off
UseIntDivNetSlope off
InlineInvariantSignals off
OptimizeBlockIOStorage on
BufferReuse on
EnhancedBackFolding off
StrengthReduction off
EnforceIntegerDowncast on
ExpressionFolding on
BooleansAsBitfields off
EnableMemcpy on
MemcpyThreshold 64
PassReuseOutputArgsAs "Structure reference"
ExpressionDepthLimit 2147483647
FoldNonRolledExpr on
LocalBlockOutputs on
RollThreshold 5
SystemCodeInlineAuto off
StateBitsets off
DataBitsets off
UseTempVars off
ZeroExternalMemoryAtStartup on
ZeroInternalMemoryAtStartup on
InitFltsAndDblsToZero off
NoFixptDivByZeroProtection off
EfficientFloat2IntCast off
EfficientMapNaN2IntZero on
OptimizeModelRefInitCode off
LifeSpan "inf"
BufferReusableBoundary on
SimCompilerOptimization "Off"
AccelVerboseBuild off
}
Simulink.DebuggingCC {
$ObjectID 5
Version "1.6.0"
RTPrefix "error"
ConsistencyChecking "none"
ArrayBoundsChecking "none"
SignalInfNanChecking "none"
SignalRangeChecking "none"
ReadBeforeWriteMsg "UseLocalSettings"
WriteAfterWriteMsg "UseLocalSettings"
WriteAfterReadMsg "UseLocalSettings"
AlgebraicLoopMsg "warning"
ArtificialAlgebraicLoopMsg "warning"
SaveWithDisabledLinksMsg "warning"
SaveWithParameterizedLinksMsg "warning"
CheckSSInitialOutputMsg on
UnderspecifiedInitializationDetection "Classic"
MergeDetectMultiDrivingBlocksExec "none"
CheckExecutionContextPreStartOutputMsg off
CheckExecutionContextRuntimeOutputMsg off
SignalResolutionControl "UseLocalSettings"
BlockPriorityViolationMsg "warning"
MinStepSizeMsg "warning"
TimeAdjustmentMsg "none"
MaxConsecutiveZCsMsg "error"
SolverPrmCheckMsg "warning"
InheritedTsInSrcMsg "warning"
DiscreteInheritContinuousMsg "warning"
MultiTaskDSMMsg "error"
MultiTaskCondExecSysMsg "error"
MultiTaskRateTransMsg "error"
SingleTaskRateTransMsg "none"
TasksWithSamePriorityMsg "warning"
SigSpecEnsureSampleTimeMsg "warning"
CheckMatrixSingularityMsg "none"
IntegerOverflowMsg "warning"
Int32ToFloatConvMsg "warning"
ParameterDowncastMsg "error"
ParameterOverflowMsg "error"
ParameterUnderflowMsg "none"
ParameterPrecisionLossMsg "warning"
ParameterTunabilityLossMsg "warning"
FixptConstUnderflowMsg "none"
FixptConstOverflowMsg "none"
FixptConstPrecisionLossMsg "none"
UnderSpecifiedDataTypeMsg "none"
UnnecessaryDatatypeConvMsg "none"
VectorMatrixConversionMsg "none"
InvalidFcnCallConnMsg "error"
FcnCallInpInsideContextMsg "Use local settings"
SignalLabelMismatchMsg "none"
UnconnectedInputMsg "warning"
UnconnectedOutputMsg "warning"
UnconnectedLineMsg "warning"
SFcnCompatibilityMsg "none"
UniqueDataStoreMsg "none"
BusObjectLabelMismatch "warning"
RootOutportRequireBusObject "warning"
AssertControl "UseLocalSettings"
EnableOverflowDetection off
ModelReferenceIOMsg "none"
ModelReferenceVersionMismatchMessage "none"
ModelReferenceIOMismatchMessage "none"
ModelReferenceCSMismatchMessage "none"
UnknownTsInhSupMsg "warning"
ModelReferenceDataLoggingMessage "warning"
ModelReferenceSymbolNameMessage "warning"
ModelReferenceExtraNoncontSigs "error"
StateNameClashWarn "warning"
SimStateInterfaceChecksumMismatchMsg "warning"
StrictBusMsg "Warning"
LoggingUnavailableSignals "error"
BlockIODiagnostic "none"
}
Simulink.HardwareCC {
$ObjectID 6
Version "1.6.0"
ProdBitPerChar 8
ProdBitPerShort 16
ProdBitPerInt 32
ProdBitPerLong 32
ProdIntDivRoundTo "Undefined"
ProdEndianess "Unspecified"
ProdWordSize 32
ProdShiftRightIntArith on
ProdHWDeviceType "32-bit Generic"
TargetBitPerChar 8
TargetBitPerShort 16
TargetBitPerInt 32
TargetBitPerLong 32
TargetShiftRightIntArith on
TargetIntDivRoundTo "Undefined"
TargetEndianess "Unspecified"
TargetWordSize 32
TargetTypeEmulationWarnSuppressLevel 0
TargetPreprocMaxBitsSint 32
TargetPreprocMaxBitsUint 32
TargetHWDeviceType "Specified"
TargetUnknown off
ProdEqTarget on
}
Simulink.ModelReferenceCC {
$ObjectID 7
Version "1.6.0"
UpdateModelReferenceTargets "IfOutOfDateOrStructuralChange"
CheckModelReferenceTargetMessage "error"
ModelReferenceNumInstancesAllowed "Multi"
ModelReferencePassRootInputsByReference on
ModelReferenceMinAlgLoopOccurrences off
}
Simulink.SFSimCC {
$ObjectID 8
Version "1.6.0"
SFSimEnableDebug on
SFSimOverflowDetection on
SFSimEcho on
SimBlas on
SimCtrlC on
SimExtrinsic on
SimIntegrity on
SimUseLocalCustomCode off
SimBuildMode "sf_incremental_build"
}
Simulink.RTWCC {
$BackupClass "Simulink.RTWCC"
$ObjectID 9
Version "1.6.0"
Array {
Type "Cell"
Dimension 6
Cell "IncludeHyperlinkInReport"
Cell "GenerateTraceInfo"
Cell "GenerateTraceReport"
Cell "GenerateTraceReportSl"
Cell "GenerateTraceReportSf"
Cell "GenerateTraceReportEml"
PropName "DisabledProps"
}
SystemTargetFile "grt.tlc"
GenCodeOnly off
MakeCommand "make_rtw"
GenerateMakefile on
TemplateMakefile "grt_default_tmf"
GenerateReport off
SaveLog off
RTWVerbose on
RetainRTWFile off
ProfileTLC off
TLCDebug off
TLCCoverage off
TLCAssert off
ProcessScriptMode "Default"
ConfigurationMode "Optimized"
ConfigAtBuild off
RTWUseLocalCustomCode off
RTWUseSimCustomCode off
IncludeHyperlinkInReport off
LaunchReport off
TargetLang "C"
IncludeBusHierarchyInRTWFileBlockHierarchyMap off
IncludeERTFirstTime off
GenerateTraceInfo off
GenerateTraceReport off
GenerateTraceReportSl off
GenerateTraceReportSf off
GenerateTraceReportEml off
GenerateCodeInfo off
RTWCompilerOptimization "Off"
CheckMdlBeforeBuild "Off"
Array {
Type "Handle"
Dimension 2
Simulink.CodeAppCC {
$ObjectID 10
Version "1.6.0"
Array {
Type "Cell"
Dimension 19
Cell "IgnoreCustomStorageClasses"
Cell "IgnoreTestpoints"
Cell "InsertBlockDesc"
Cell "SFDataObjDesc"
Cell "SimulinkDataObjDesc"
Cell "DefineNamingRule"
Cell "SignalNamingRule"
Cell "ParamNamingRule"
Cell "InlinedPrmAccess"
Cell "CustomSymbolStr"
Cell "CustomSymbolStrGlobalVar"
Cell "CustomSymbolStrType"
Cell "CustomSymbolStrField"
Cell "CustomSymbolStrFcn"
Cell "CustomSymbolStrFcnArg"
Cell "CustomSymbolStrBlkIO"
Cell "CustomSymbolStrTmpVar"
Cell "CustomSymbolStrMacro"
Cell "ReqsInCode"
PropName "DisabledProps"
}
ForceParamTrailComments off
GenerateComments on
IgnoreCustomStorageClasses on
IgnoreTestpoints off
IncHierarchyInIds off
MaxIdLength 31
PreserveName off
PreserveNameWithParent off
ShowEliminatedStatement off
IncAutoGenComments off
SimulinkDataObjDesc off
SFDataObjDesc off
IncDataTypeInIds off
MangleLength 1
CustomSymbolStrGlobalVar "$R$N$M"
CustomSymbolStrType "$N$R$M"
CustomSymbolStrField "$N$M"
CustomSymbolStrFcn "$R$N$M$F"
CustomSymbolStrFcnArg "rt$I$N$M"
CustomSymbolStrBlkIO "rtb_$N$M"
CustomSymbolStrTmpVar "$N$M"
CustomSymbolStrMacro "$R$N$M"
DefineNamingRule "None"
ParamNamingRule "None"
SignalNamingRule "None"
InsertBlockDesc off
SimulinkBlockComments on
EnableCustomComments off
InlinedPrmAccess "Literals"
ReqsInCode off
UseSimReservedNames off
}
Simulink.GRTTargetCC {
$BackupClass "Simulink.TargetCC"
$ObjectID 11
Version "1.6.0"
Array {
Type "Cell"
Dimension 17
Cell "GeneratePreprocessorConditionals"
Cell "IncludeMdlTerminateFcn"
Cell "CombineOutputUpdateFcns"
Cell "SuppressErrorStatus"
Cell "ERTCustomFileBanners"
Cell "GenerateSampleERTMain"
Cell "GenerateTestInterfaces"
Cell "ModelStepFunctionPrototypeControlCompliant"
Cell "CPPClassGenCompliant"
Cell "MultiInstanceERTCode"
Cell "PurelyIntegerCode"
Cell "SupportNonFinite"
Cell "SupportComplex"
Cell "SupportAbsoluteTime"
Cell "SupportContinuousTime"
Cell "SupportNonInlinedSFcns"
Cell "PortableWordSizes"
PropName "DisabledProps"
}
TargetFcnLib "ansi_tfl_table_tmw.mat"
TargetLibSuffix ""
TargetPreCompLibLocation ""
TargetFunctionLibrary "ANSI_C"
UtilityFuncGeneration "Auto"
ERTMultiwordTypeDef "System defined"
ERTMultiwordLength 256
MultiwordLength 2048
GenerateFullHeader on
GenerateSampleERTMain off
GenerateTestInterfaces off
IsPILTarget off
ModelReferenceCompliant on
ParMdlRefBuildCompliant on
CompOptLevelCompliant on
IncludeMdlTerminateFcn on
GeneratePreprocessorConditionals "Disable all"
CombineOutputUpdateFcns off
SuppressErrorStatus off
ERTFirstTimeCompliant off
IncludeFileDelimiter "Auto"
ERTCustomFileBanners off
SupportAbsoluteTime on
LogVarNameModifier "rt_"
MatFileLogging on
MultiInstanceERTCode off
SupportNonFinite on
SupportComplex on
PurelyIntegerCode off
SupportContinuousTime on
SupportNonInlinedSFcns on
SupportVariableSizeSignals off
EnableShiftOperators on
ParenthesesLevel "Nominal"
PortableWordSizes off
ModelStepFunctionPrototypeControlCompliant off
CPPClassGenCompliant off
AutosarCompliant off
UseMalloc off
ExtMode off
ExtModeStaticAlloc off
ExtModeTesting off
ExtModeStaticAllocSize 1000000
ExtModeTransport 0
ExtModeMexFile "ext_comm"
ExtModeIntrfLevel "Level1"
RTWCAPISignals off
RTWCAPIParams off
RTWCAPIStates off
GenerateASAP2 off
}
PropName "Components"
}
}
hdlcoderui.hdlcc {
$ObjectID 12
Version "1.6.0"
Description "HDL Coder custom configuration component"
Name "HDL Coder"
Array {
Type "Cell"
Dimension 1
Cell ""
PropName "HDLConfigFile"
}
HDLCActiveTab "0"
}
PropName "Components"
}
Name "Configuration"
CurrentDlgPage "Solver"
ConfigPrmDlgPosition " [ 280, 135, 1160, 765 ] "
}
PropName "ConfigurationSets"
}
Simulink.ConfigSet {
$PropName "ActiveConfigurationSet"
$ObjectID 1
}
BlockDefaults {
ForegroundColor "black"
BackgroundColor "white"
DropShadow off
NamePlacement "normal"
FontName "Helvetica"
FontSize 10
FontWeight "normal"
FontAngle "normal"
ShowName on
BlockRotation 0
BlockMirror off
}
AnnotationDefaults {
HorizontalAlignment "center"
VerticalAlignment "middle"
ForegroundColor "black"
BackgroundColor "white"
DropShadow off
FontName "Helvetica"
FontSize 10
FontWeight "normal"
FontAngle "normal"
UseDisplayTextAsClickCallback off
}
LineDefaults {
FontName "Helvetica"
FontSize 9
FontWeight "normal"
FontAngle "normal"
}
BlockParameterDefaults {
Block {
BlockType Demux
Outputs "4"
DisplayOption "none"
BusSelectionMode off
}
Block {
BlockType Inport
Port "1"
UseBusObject off
BusObject "BusObject"
BusOutputAsStruct off
PortDimensions "-1"
VarSizeSig "Inherit"
SampleTime "-1"
OutMin "[]"
OutMax "[]"
DataType "auto"
OutDataType "fixdt(1,16,0)"
OutScaling "[]"
OutDataTypeStr "Inherit: auto"
LockScale off
SignalType "auto"
SamplingMode "auto"
LatchByDelayingOutsideSignal off
LatchByCopyingInsideSignal off
Interpolate on
}
Block {
BlockType "S-Function"
FunctionName "system"
SFunctionModules "''"
PortCounts "[]"
SFunctionDeploymentMode off
}
Block {
BlockType SubSystem
ShowPortLabels "FromPortIcon"
Permissions "ReadWrite"
PermitHierarchicalResolution "All"
TreatAsAtomicUnit off
CheckFcnCallInpInsideContextMsg off
SystemSampleTime "-1"
RTWFcnNameOpts "Auto"
RTWFileNameOpts "Auto"
RTWMemSecFuncInitTerm "Inherit from model"
RTWMemSecFuncExecute "Inherit from model"
RTWMemSecDataConstants "Inherit from model"
RTWMemSecDataInternal "Inherit from model"
RTWMemSecDataParameters "Inherit from model"
SimViewingDevice off
DataTypeOverride "UseLocalSettings"
MinMaxOverflowLogging "UseLocalSettings"
}
Block {
BlockType Terminator
}
}
System {
Name "trajectory2"
Location [715, 251, 1295, 511]
Open on
ModelBrowserVisibility off
ModelBrowserWidth 200
ScreenColor "white"
PaperOrientation "landscape"
PaperPositionMode "auto"
PaperType "A4"
PaperUnits "centimeters"
TiledPaperMargins [1.270000, 1.270000, 1.270000, 1.270000]
TiledPageScale 1
ShowPageBoundaries off
ZoomFactor "100"
ReportName "simulink-default.rpt"
SIDHighWatermark 2
Block {
BlockType SubSystem
Name "Embedded\nMATLAB Function"
SID 1
Ports [1]
Position [305, 75, 375, 125]
LibraryVersion "1.30"
PermitHierarchicalResolution "ExplicitOnly"
MinAlgLoopOccurrences off
PropExecContextOutsideSubsystem off
RTWSystemCode "Auto"
FunctionWithSeparateData off
Opaque off
Array {
Type "Handle"
Dimension 0
PropName "AvailSigsLoadSave"
}
RequestExecContextInheritance off
MaskHideContents off
MaskType "Stateflow"
MaskDescription "Embedded MATLAB block"
MaskDisplay "disp('fcn');"
MaskSelfModifiable on
MaskIconFrame on
MaskIconOpaque off
MaskIconRotate "none"
MaskPortRotate "default"
MaskIconUnits "autoscale"
System {
Name "Embedded\nMATLAB Function"
Location [257, 457, 812, 717]
Open off
ModelBrowserVisibility off
ModelBrowserWidth 200
ScreenColor "white"
PaperOrientation "landscape"
PaperPositionMode "auto"
PaperType "A4"
PaperUnits "centimeters"
TiledPaperMargins [1.270000, 1.270000, 1.270000, 1.270000]
TiledPageScale 1
ShowPageBoundaries off
ZoomFactor "100"
SIDHighWatermark 11
SIDPrevWatermark 11
Block {
BlockType Inport
Name "data"
SID 1
Position [20, 101, 40, 119]
IconDisplay "Port number"
OutDataType "sfix(16)"
OutScaling "2^0"
}
Block {
BlockType Demux
Name " Demux "
SID 7
Ports [1, 1]
Position [270, 100, 320, 140]
Outputs "1"
}
Block {
BlockType "S-Function"
Name " SFunction "
SID 6
Tag "Stateflow S-Function trajectory2 2"
Ports [1, 1]
Position [180, 100, 230, 180]
FunctionName "sf_sfun"
PortCounts "[1 1]"
EnableBusSupport on
}
Block {
BlockType Terminator
Name " Terminator "
SID 9
Position [460, 111, 480, 129]
}
Line {
SrcBlock " SFunction "
SrcPort 1
DstBlock " Demux "
DstPort 1
}
Line {
SrcBlock "data"
SrcPort 1
DstBlock " SFunction "
DstPort 1
}
Line {
SrcBlock " Demux "
SrcPort 1
DstBlock " Terminator "
DstPort 1
}
}
}
Block {
BlockType Reference
Name "TCP/IP Receive"
SID 2
Ports [0, 1]
Position [55, 77, 165, 123]
LibraryVersion "1.84"
DialogController "instrumentcreatedialog"
DialogControllerArgs "DataTag0"
SourceBlock "instrumentlib/TCP//IP Receive"
SourceType "TCP/IP Receive"
Host "127.0.0.1"
Port "80"
DataSize "[1 3]"
EnableBlockingMode on
Timeout "10"
SampleTime "0.01"
DataType "double"
ByteOrder "BigEndian"
}
Line {
SrcBlock "TCP/IP Receive"
SrcPort 1
DstBlock "Embedded\nMATLAB Function"
DstPort 1
}
}
}
MatData {
NumRecords 1
DataRecord {
Tag DataTag0
Data " %)30 . : 8 ( 0 % \" $ ! 0 . . 8 ( ! "
" % \" $ ' 0 0 !P '1C<&EP<F( "
}
}
# Finite State Machines
#
# Stateflow Version 7.1 (R2009a) dated Jul 17 2009, 00:35:51
#
#
Stateflow {
machine {
id 1
name "trajectory2"
created "23-Feb-2010 11:53:03"
isLibrary 0
firstTarget 8
sfVersion 71014000.00001
}
chart {
id 2
name "Embedded\nMATLAB Function"
windowPosition [353.175 315 200.25 189.75]
viewLimits [0 156.75 0 153.75]
screen [1 1 1440 900 1.25]
treeNode [0 3 0 0]
firstTransition 5
firstJunction 4
viewObj 2
machine 1
toolbarMode LIBRARY_TOOLBAR
ssIdHighWaterMark 7
decomposition CLUSTER_CHART
type EML_CHART
firstData 6
chartFileNumber 2
disableImplicitCasting 1
eml {
name "fcn"
}
}
state {
id 3
labelString "eML_blk_kernel()"
position [18 64.5 118 66]
fontSize 12
chart 2
treeNode [2 0 0 0]
superState SUBCHART
subviewer 2
ssIdNumber 1
type FUNC_STATE
decomposition CLUSTER_STATE
eml {
isEML 1
script "function fcn(data)\n%#eml\neml.extrinsic('figure','scatter3','grid','hold','axis')\nfigure(1);\n%"
"hold on\n\nscatter3(data(1),data(2),data(3))\n%scatter3(data,10,10)\n%axis on\ngrid"
editorLayout "100 M4x1[205 142 1080 733]"
}
}
junction {
id 4
position [23.5747 49.5747 7]
chart 2
linkNode [2 0 0]
subviewer 2
ssIdNumber 3
type CONNECTIVE_JUNCTION
}
transition {
id 5
labelString "{eML_blk_kernel();}"
labelPosition [32.125 19.875 102.544 14.964]
fontSize 12
src {
intersection [0 0 1 0 23.5747 14.625 0 0]
}
dst {
id 4
intersection [7 0 -1 -1 23.5747 42.5747 0 0]
}
midPoint [23.5747 24.9468]
chart 2
linkNode [2 0 0]
dataLimits [23.575 23.575 14.625 34.575]
subviewer 2
drawStyle SMART
executionOrder 1
ssIdNumber 2
}
data {
id 6
ssIdNumber 4
name "data"
linkNode [2 0 0]
scope INPUT_DATA
machine 1
props {
array {
size "-1"
}
type {
method SF_INHERITED_TYPE
primitive SF_DOUBLE_TYPE
}
complexity SF_COMPLEX_INHERITED
}
dataType "Inherit: Same as Simulink"
}
instance {
id 7
name "Embedded\nMATLAB Function"
machine 1
chart 2
}
target {
id 8
name "sfun"
description "Default Simulink S-Function Target."
machine 1
linkNode [1 0 0]
}
}
I can't see creating socket and binding to it in your C code. Are you sure that you're binding on 127.0.0.1 and port 80? Are you sure that there's no some apache running on the server on port 80?
http://www.linuxhowtos.org/C_C++/socket.htm
Also:
sock_err = send(csock, T, 3*sizeof(double), 0);
I don't also see T in your code, which is probably not the issue, but it doesn't seem to be the datasend pointer to mxArray.
Related
How to capture multiple instances of the same group in Rust regex?
Here is my text: hello: 3 32 2 8 I want to capture it with the following regex: ^([a-z]+):( [0-9]+)+$ I'm doing this: let txt = "hello: 3 32 2 8"; let re = Regex::new("^([a-z]+):( [0-9]+)+$")?; let caps = re.captures(txt); println!("{caps:?}"); I'm getting only the last number 8 in the second capture group: Some(Captures({0: Some("hello: 3 32 2 8"), 1: Some("hello"), 2: Some(" 8")})) I suspect that it is an expected behavior of captures, but what is the workaround?
I would simply capture the whole sequence of integers. Since we know this substring has the expected shape, we can split and parse it with confidence (except if one integer has too many digits). Note that I added some tolerance around white-spaces. use regex::Regex; fn detect(txt: &str) -> Result<(&str, Vec<u32>), Box<dyn std::error::Error>> { let re = Regex::new(r"^\s*([a-z]+)\s*:((\s*[0-9]+)+)\s*$")?; let caps = re.captures(txt).ok_or("no match")?; // starting from here, we know that all the expected substrings exist // thus we can unwrap() the options/errors let name = caps.get(1).unwrap().as_str(); let values = caps .get(2) .unwrap() .as_str() .split_ascii_whitespace() .filter_map(|s| s.parse().ok()) // FIXME: overflow ignored .collect(); Ok((name, values)) } fn main() { for txt in [ "hello: 3 32 2 8", "hello :\t3 32 2 8", "\thello :\t3 32 2 8 ", "hello:", "hello:9999999999 3", ] { println!("{:?} ~~> {:?}", txt, detect(txt)); } } /* "hello: 3 32 2 8" ~~> Ok(("hello", [3, 32, 2, 8])) "hello :\t3 32 2 8" ~~> Ok(("hello", [3, 32, 2, 8])) "\thello :\t3 32 2 8 " ~~> Ok(("hello", [3, 32, 2, 8])) "hello:" ~~> Err("no match") "hello:9999999999 3" ~~> Ok(("hello", [3])) */
What regex pattern matches this string?
Been scratching my head on this for hours to no avail! I need to match 3 different parts of this string, in 3 different patterns. So one regex pattern matches the first, etc. Here is the string: { "jsonrpc": "2.0", "result": [ { "marketId": "1.123485047", "isMarketDataDelayed": false, "status": "OPEN", "betDelay": 0, "bspReconciled": false, "complete": true, "inplay": false, "numberOfWinners": 1, "numberOfRunners": 3, "numberOfActiveRunners": 3, "lastMatchTime": "2016-03-18T23:21:14.211Z", "totalMatched": 47663.09, "totalAvailable": 140527.57, "crossMatching": true, "runnersVoidable": false, "version": 1259153627, "runners": [ { "selectionId": 48224, "handicap": 0.0, "status": "ACTIVE", "lastPriceTraded": 1.57, "totalMatched": 37408.96, "ex": { "availableToBack": [ { "price": 1.56, "size": 1344.78 }, { "price": 1.55, "size": 642.45 }, { "price": 1.54, "size": 1034.4 } ], "availableToLay": [ { "price": 1.57, "size": 303.34 }, { "price": 1.58, "size": 2368.34 }, { "price": 1.59, "size": 1220.99 } ], "tradedVolume": [] } }, { "selectionId": 1141, "handicap": 0.0, "status": "ACTIVE", "lastPriceTraded": 7.0, "totalMatched": 5863.62, "ex": { "availableToBack": [ { "price": 7.0, "size": 286.85 }, { "price": 6.8, "size": 552.02 }, { "price": 6.6, "size": 25.81 } ], "availableToLay": [ { "price": 7.2, "size": 36.05 }, { "price": 7.4, "size": 312.79 }, { "price": 7.6, "size": 92.63 } ], "tradedVolume": [] } }, { "selectionId": 58805, "handicap": 0.0, "status": "ACTIVE", "lastPriceTraded": 4.5, "totalMatched": 4390.5, "ex": { "availableToBack": [ { "price": 4.5, "size": 209.65 }, { "price": 4.4, "size": 692.37 }, { "price": 4.3, "size": 429.69 } ], "availableToLay": [ { "price": 4.6, "size": 279.02 }, { "price": 4.7, "size": 821.2 }, { "price": 4.8, "size": 928.88 } ], "tradedVolume": [] } } ] } ], "id": 1 } I bolded the 3 parts which need extracting. (in this case they are 1.57, 7.2 and 4.6). These numbers can be integers, have 1 or 2 decimals.
One possible regex to extract 1.57, 7.2 and 4.6 would be : (?:availableToLay[^\d]+)([\d.]+) https://regex101.com/r/vP5iH2/1
UPDATE: Just seen the answer from "florentbr" and that is a much tidier answer than mine! Do you really need RegEx? There's probably many ways of doing this, but breaking down by commas seems to hit the right data. Open up Excel, and dump your data in Cell "A1", then past this code into the VBA editor: Option Explicit Sub getYourVals() Dim dataStr() As String Dim i As Integer Dim marker As String marker = "availableToLay" dataStr = Split(Range("A" & 1).Value, ",") For i = 1 To UBound(dataStr) If Mid(dataStr(i), 2, Len(marker)) = marker Then Debug.Print Mid(dataStr(i), 28, Len(dataStr(i)) - 27) End If Range("A" & i + 1).Value = dataStr(i) Next i End Sub
Consider parsing the JSON string altogether, flattening it for needed data. JSON formats can be thought of as an assembly of dictionaries and collections, two data structures VBA maintains. Below uses VBA Tools' VBA-JSON library. Setup Steps Import the .bas file in above link into a VBA module in IDE. Add the VBA Reference for Microsoft Scripting Runtime VBA Script (loops through the results, runners, and ex collections) Sub JSONStringData() Dim jsonStr As String Dim element As Variant, e As Variant, n As Variant, r As Variant Dim x As Variant, s As Variant, pr As Variant, dat As Variant Dim i As Integer, num As Integer jsonStr = "{""jsonrpc"":""2.0"",""result"":" _ & "[{""marketId"":""1.123485047"",""isMarketDataDelayed"":false,""status"":""OPEN""," _ & """betDelay"":0,""bspReconciled"":false,""complete"":true,""inplay"":false," _ & """numberOfWinners"":1,""numberOfRunners"":3,""numberOfActiveRunners"":3,""lastMatchTime"":" _ & """2016-03-18T23:21:14.211Z"",""totalMatched"":47663.09,""totalAvailable"":140527.57,""crossMatching"":true," _ & """runnersVoidable"":false,""version"":1259153627,""runners"":" _ & "[{""selectionId"":48224,""handicap"":0.0,""status"":""ACTIVE"",""lastPriceTraded"":1.57," _ & """totalMatched"":37408.96,""ex"":{""availableToBack"":[{""price"":1.56,""size"":1344.78}," _ & "{""price"":1.55,""size"":642.45},{""price"":1.54,""size"":1034.4}],""availableToLay"":" _ & "[{""price"":1.57,""size"":303.34},{""price"":1.58,""size"":2368.34},{""price"":1.59,""size"":1220.99}]," _ & """tradedVolume"":[]}},{""selectionId"":1141,""handicap"":0.0,""status"":""ACTIVE""," _ & """lastPriceTraded"":7.0,""totalMatched"":5863.62,""ex"":{""availableToBack"":[{""price"":7.0," _ & """size"":286.85},{""price"":6.8,""size"":552.02},{""price"":6.6,""size"":25.81}],""availableToLay"":" _ & "[{""price"":7.2,""size"":36.05},{""price"":7.4,""size"":312.79},{""price"":7.6,""size"":" _ & "92.63}],""tradedVolume"":[]}},{""selectionId"":58805,""handicap"":0.0,""status"":" _ & """ACTIVE"",""lastPriceTraded"":4.5,""totalMatched"":4390.5,""ex"":{""availableToBack"":" _ & "[{""price"":4.5,""size"":209.65},{""price"":4.4,""size"":692.37},{""price"":4.3,""size"":429.69}]" _ & ",""availableToLay"":[{""price"":4.6,""size"":279.02},{""price"":4.7,""size"":821.2}," _ & "{""price"":4.8,""size"":928.88}],""tradedVolume"":[]}}]}],""id"":1}" ' PARSE FILE STRING Dim p As Object Set p = ParseJson(jsonStr) i = 5 For Each element In p ' RESULT COLLECTION OF DICTIONARIES (N = 17) If element = "result" Then For Each e In p(element) For Each n In e ' RUNNERS COLLECTION OF DICTIONARIES (N = 6) If n = "runners" Then For Each r In e(n) For Each x In r ' EX DICTIONARY OF COLLECTIONS (N = 9, 3 PER 3 RUNNERS) If x = "ex" Then For Each s In r(x) num = 1 For Each pr In r(x)(s) For Each dat In pr Sheets(1).Range("A" & i) = r("selectionId") Sheets(1).Range("B" & i) = r("handicap") Sheets(1).Range("C" & i) = r("status") Sheets(1).Range("D" & i) = r("lastPriceTraded") Sheets(1).Range("E" & i) = r("totalMatched") Sheets(1).Range("F" & i) = s Sheets(1).Range("G" & i) = num Sheets(1).Range("H" & i) = dat Sheets(1).Range("I" & i) = pr(dat) i = i + 1 Next dat num = num + 1 Next pr Next s End If Next x Next r End If Next n Next e End If Next element End Sub Result (where 1.57, 7.2, and 4.6 are the first prices for availableToLay for each of three runners) 48224 0 ACTIVE 1.57 37408.96 availableToBack 1 price 1.56 48224 0 ACTIVE 1.57 37408.96 availableToBack 1 size 1344.78 48224 0 ACTIVE 1.57 37408.96 availableToBack 2 price 1.55 48224 0 ACTIVE 1.57 37408.96 availableToBack 2 size 642.45 48224 0 ACTIVE 1.57 37408.96 availableToBack 3 price 1.54 48224 0 ACTIVE 1.57 37408.96 availableToBack 3 size 1034.4 48224 0 ACTIVE 1.57 37408.96 availableToLay 1 price 1.57 48224 0 ACTIVE 1.57 37408.96 availableToLay 1 size 303.34 48224 0 ACTIVE 1.57 37408.96 availableToLay 2 price 1.58 48224 0 ACTIVE 1.57 37408.96 availableToLay 2 size 2368.34 48224 0 ACTIVE 1.57 37408.96 availableToLay 3 price 1.59 48224 0 ACTIVE 1.57 37408.96 availableToLay 3 size 1220.99 1141 0 ACTIVE 7 5863.62 availableToBack 1 price 7 1141 0 ACTIVE 7 5863.62 availableToBack 1 size 286.85 1141 0 ACTIVE 7 5863.62 availableToBack 2 price 6.8 1141 0 ACTIVE 7 5863.62 availableToBack 2 size 552.02 1141 0 ACTIVE 7 5863.62 availableToBack 3 price 6.6 1141 0 ACTIVE 7 5863.62 availableToBack 3 size 25.81 1141 0 ACTIVE 7 5863.62 availableToLay 1 price 7.2 1141 0 ACTIVE 7 5863.62 availableToLay 1 size 36.05 1141 0 ACTIVE 7 5863.62 availableToLay 2 price 7.4 1141 0 ACTIVE 7 5863.62 availableToLay 2 size 312.79 1141 0 ACTIVE 7 5863.62 availableToLay 3 price 7.6 1141 0 ACTIVE 7 5863.62 availableToLay 3 size 92.63 58805 0 ACTIVE 4.5 4390.5 availableToBack 1 price 4.5 58805 0 ACTIVE 4.5 4390.5 availableToBack 1 size 209.65 58805 0 ACTIVE 4.5 4390.5 availableToBack 2 price 4.4 58805 0 ACTIVE 4.5 4390.5 availableToBack 2 size 692.37 58805 0 ACTIVE 4.5 4390.5 availableToBack 3 price 4.3 58805 0 ACTIVE 4.5 4390.5 availableToBack 3 size 429.69 58805 0 ACTIVE 4.5 4390.5 availableToLay 1 price 4.6 58805 0 ACTIVE 4.5 4390.5 availableToLay 1 size 279.02 58805 0 ACTIVE 4.5 4390.5 availableToLay 2 price 4.7 58805 0 ACTIVE 4.5 4390.5 availableToLay 2 size 821.2 58805 0 ACTIVE 4.5 4390.5 availableToLay 3 price 4.8 58805 0 ACTIVE 4.5 4390.5 availableToLay 3 size 928.88
QSqlQuery ignoring sort order for SQLite DB
The results returned by my QSqlQuery are always in the same order, regardless of the ORDER BY state: void Sy_loggingModel::reload() { auto query = d_->buildQuery(); query.setForwardOnly( true ); if ( !query.exec() ) { throw Sy_exception( QObject::tr( "Failed to query logging data: " ) + query.lastError().text() ); } beginResetModel(); qDebug() << query.lastQuery() << d_->filter_ // First ? param << d_->sortedColumn_; // Second ? param d_->entries_.clear(); while ( query.next() ) { auto timestamp = query.value( 1 ).toLongLong(); auto level = query.value( 2 ).toInt(); d_->entries_ << Sy_loggingModel_d::Entry{ query.value( 0 ).toLongLong(), QDateTime::fromMSecsSinceEpoch( timestamp ).toString(), static_cast< Sy_loggerInterface::DebugLevel >( level ), query.value( 3 ).toString() }; qDebug() << "\t" << query.value( 0 ).toLongLong() << timestamp << level << query.value( 3 ).toString(); } endResetModel(); } Produces this output when alternating between sort orders: "SELECT rowid, timestamp, debugLevel, message FROM Sy_logger WHERE rowid >= ? AND debugLevel IN ( 0, 1, 2 ) ORDER BY ? DESC;" 0 1 1 1415399097350 0 "Opened database ./logs/Syren2.log" 2 1415399097382 1 "Listening on port 23000" 3 1415399418377 2 "New log rotation settings received, Metric: 0, Interval: 720" 4 1416178611851 2 "Opened database ./logs/Syren2.log" 5 1416178611852 2 "Listening on port 23000" 6 1416178612776 2 "New log rotation settings received, Metric: 0, Interval: 720" "SELECT rowid, timestamp, debugLevel, message FROM Sy_logger WHERE rowid >= ? AND debugLevel IN ( 0, 1, 2 ) ORDER BY ? ASC;" 0 1 1 1415399097350 0 "Opened database ./logs/Syren2.log" 2 1415399097382 1 "Listening on port 23000" 3 1415399418377 2 "New log rotation settings received, Metric: 0, Interval: 720" 4 1416178611851 2 "Opened database ./logs/Syren2.log" 5 1416178611852 2 "Listening on port 23000" 6 1416178612776 2 "New log rotation settings received, Metric: 0, Interval: 720" The SQL statement returns the expected result set when used from the command line. Any suggestions? I'm using Qt v5.3.2.
The documentation says: If the ORDER BY expression is a constant integer K then the expression is considered an alias for the K-th column of the result set. However, parameters are not considered constants, so the value you use for this parameters is used as an expression that happens to be the same for all rows. If you want to sort by different columns, you have to construct the SQL statement dynamically.
Rally Rest Api: Get defect by Formatted Id
Hi I am having a web service. https://rally1.rallydev.com/slm/webservice/v2.x/defect/objectId What I want to do is instead of objectId search defect by using Formatted Id. How can I do it?
You can find appropriate objectId by formattedID using Rally Lookback API request. For example: I need search objectId of Test Case named TC12345. So I must send following GET query: https://rally1.rallydev.com/analytics/v2.0/service/rally/workspace/WORKSPACE_ID/artifact/snapshot/query.js?find={"_UnformattedID":12345,"_TypeHierarchy":"TestCase"}&fields=["ObjectID"] Where: WORKSPACE_ID is the your workspace personal number which you can obtain on this page https://rally1.rallydev.com/slm/doc/webservice/objectModel.sp UnformattedID = 12345 = numerial part of TC12345 Output can be (see searched "ObjectID: 22697085352" at the very end): { _rallyAPIMajor: "2" _rallyAPIMinor: "0" Errors: [0] Warnings: [0] ThreadStats: { cpuTime: "10.0" waitTime: "0" blockedTime: "1" waitCount: "1" blockedCount: "2" }- Timings: { preProcess: 0 findEtlDate: 36 allowedValuesDisambiguation: 1 mongoQuery: 9 authorization: 3 formattedId: 0 suppressNonRequested: 0 allowedValuesHydration: 0 compressSnapshots: 0 TOTAL: 49 }- GeneratedQuery: { find: { _UnformattedID: 619 _TypeHierarchy: { $in: [3] 0: -51012 1: 9467271631 2: 10486304042 - }- _ValidFrom: { $lte: "2014-09-16T14:21:35.731Z" }- }- limit: 100 skip: 0 fields: { ObjectID: 1 Project: 1 }- }- TotalResultCount: 1 StartIndex: 0 PageSize: 100 ETLDate: "2014-09-16T14:21:35.731Z" Results: [1] 0: { ObjectID: 22697085352 }- - }
It is easier if you use "query" parameter over defect entity directly like: https://eu1.rallydev.com/slm/webservice/v2.0/defect?query=(FormattedID = DEXXXXX)&fetch=Name,ObjectID Regards.
IF function; struggling with format of 3 times greater section
Excel 2002: Write an IF function for cell J8 that assigns the text "OK" if the value in cell L9 is three times greater than the value in cell M6; otherwise, have the IF function assign the text "Not OK" to cell J8. would it be: =if(L9*3>m6, "OK", "Not OK")
That would be =IF(L9>=M6*3,"OK", "Not OK") further examples: A B C Formula ------------------------------------------------- 1 2 No OK IF(B2 >= A2*3,"OK", "Not OK") 2 6 OK IF(B3 >= A3*3,"OK", "Not OK") 3 8 No OK IF(B4 >= A4*3,"OK", "Not OK")