Parsing Serial Data - An Example


Recommended Posts

If its of any value to readers -

 

Streaming serial data from a wind monitor (Serial_Mirror_1) required the Dn (Nominal direction), Sm (Mean speed) and Sx (Gust speed) taken from it:

 

Rx (08:11:45.363): 0r1,Dn=160D,Dm=163D,Dx=168D,Sn=9.3N,Sm=9.7N,Sx=10.0NL|H\013\000\010

Rx (08:11:50.360): 0r1,Dn=171D,Dm=172D,Dx=173D,Sn=9.4N,Sm=9.7N,Sx=9.9NAdk\013\000\010

 

With:

 

device.Serial_Mirror_1.purge()

while(1)
 try
  // Read in the line of data from the stream
  private string datain = device.Serial_Mirror_1.readUntil(13)
  
  // Split the data into individual items based on a comma separator
  // in the input
  private string items = parse(datain, -1, ",")
  
  private numEntries = NumRows(items)
  
  // Go through each one and pull off the value
  for (Private.index = 0, index < numEntries, index++)
   
   // Split each item into its parts based on equals sign
   private string itemParts = parse(items[index], -1, "=")
   
   // Set the code to the first part, remove leading
   // and trailing spaces
   private string code = LTrim(RTrim(itemParts[0]))
  
   // Check the code is 2 characters
   if (GetLength(code) == 2)
     
    // Get the value
    private string reading = itemParts[1]
       
    // Process based on code and write to appropriate channel
    switch
     case (CompareNoCase(code, "Dn") == 0)// Wind Direction
      Dn.AddValue(strToDouble(reading))
     case (CompareNoCase(code, "Sm") == 0) // Nominal Wind Speed
      Sm.AddValue(strToDouble(reading))
     case (CompareNoCase(code, "Sx") == 0) // Maximum Wind Speed
      Sx.AddValue(strToDouble(reading))
    endcase
   endif
  endfor
 catch()
  ? strLastError
  delay(0.05)
 endcatch

 delay(0.05)
 
endwhile

 

Link to comment
Share on other sites

Nice example, thanks!

Minor suggestion for improvement: filter for the variables of interest sooner. If the instrument returned 100 different readings and you were only interested in two, this would still step through all 100. Extract the items of interest earlier on, maybe after the initial Parse(), then step through only those. At least break out of the for() once you've found all the ones you want.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.