smb2-dissector: learn the "REPLAY_OPERATION" flag
[obnox/wireshark/wip.git] / epan / dissectors / packet-synphasor.c
1 /* packet-synphasor.c
2  * Dissector for IEEE C37.118 synchrophasor frames.
3  *
4  * Copyright 2008, Jens Steinhauser <jens.steinhauser@omicron.at>
5  *
6  * $Id$
7  *
8  * Wireshark - Network traffic analyzer
9  * By Gerald Combs <gerald@wireshark.org>
10  * Copyright 1998 Gerald Combs
11  *
12  * This program is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU General Public License
14  * as published by the Free Software Foundation; either version 2
15  * of the License, or (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25  */
26
27 #ifdef HAVE_CONFIG_H
28 #       include "config.h"
29 #endif
30
31 #include <glib.h>
32 #include <epan/conversation.h>
33 #include <epan/crc16-tvb.h>
34 #include <epan/dissectors/packet-tcp.h>
35 #include <epan/packet.h>
36 #include <epan/prefs.h>
37
38 #include <math.h>
39
40 #define PROTOCOL_NAME       "IEEE C37.118 Synchrophasor Protocol"
41 #define PROTOCOL_SHORT_NAME "SYNCHROPHASOR"
42 #define PROTOCOL_ABBREV     "synphasor"
43
44 /* forward references */
45 void proto_reg_handoff_synphasor(void);
46
47 /* global variables */
48
49 static int     proto_synphasor   = -1;
50 static GSList *config_frame_list = NULL;
51
52 /* user preferences */
53 static guint global_pref_tcp_port = 4712;
54 static guint global_pref_udp_port = 4713;
55
56 /* the ett... variables hold the state (open/close) of the treeview in the GUI */
57 static gint ett_synphasor          = -1; /* root element for this protocol */
58   /* used in the common header */
59   static gint ett_frtype           = -1;
60   static gint ett_timequal         = -1;
61   /* used for config frames */
62   static gint ett_conf             = -1;
63     static gint ett_conf_station   = -1;
64       static gint ett_conf_format  = -1;
65       static gint ett_conf_phnam   = -1;
66       static gint ett_conf_annam   = -1;
67       static gint ett_conf_dgnam   = -1;
68       static gint ett_conf_phconv  = -1;
69       static gint ett_conf_anconv  = -1;
70       static gint ett_conf_dgmask  = -1;
71   /* used for data frames */
72   static gint ett_data             = -1;
73     static gint ett_data_block     = -1;
74       static gint ett_data_stat    = -1;
75       static gint ett_data_phasors = -1;
76       static gint ett_data_analog  = -1;
77       static gint ett_data_digital = -1;
78   /* used for command frames */
79   static gint ett_command          = -1;
80
81 /* handles to the header fields hf[] in proto_register_synphasor() */
82 static int hf_sync                  = -1;
83 static int hf_sync_frtype           = -1;
84 static int hf_sync_version          = -1;
85 static int hf_idcode                = -1;
86 static int hf_frsize                = -1;
87 static int hf_soc                   = -1;
88 static int hf_timeqal_lsdir         = -1;
89 static int hf_timeqal_lsocc         = -1;
90 static int hf_timeqal_lspend        = -1;
91 static int hf_timeqal_timequalindic = -1;
92 static int hf_fracsec               = -1;
93 static int hf_conf_timebase         = -1;
94 static int hf_conf_numpmu           = -1;
95 static int hf_conf_formatb3         = -1;
96 static int hf_conf_formatb2         = -1;
97 static int hf_conf_formatb1         = -1;
98 static int hf_conf_formatb0         = -1;
99 static int hf_conf_fnom             = -1;
100 static int hf_conf_cfgcnt           = -1;
101 static int hf_data_statb15          = -1;
102 static int hf_data_statb14          = -1;
103 static int hf_data_statb13          = -1;
104 static int hf_data_statb12          = -1;
105 static int hf_data_statb11          = -1;
106 static int hf_data_statb10          = -1;
107 static int hf_data_statb05to04      = -1;
108 static int hf_data_statb03to00      = -1;
109 static int hf_command               = -1;
110
111 /* the five different frame types for this protocol */
112 enum FrameType {
113         DATA = 0,
114         HEADER,
115         CFG1,
116         CFG2,
117         CMD
118 };
119
120 /* the channel names in the protocol are all 16 bytes
121  * long (and don't have to be NULL terminated) */
122 #define CHNAM_LEN 16
123
124 /* Structures to save CFG frame content. */
125
126 /* type to indicate the format for (D)FREQ/PHASORS/ANALOG in data frame  */
127 typedef enum { integer,         /* 16 bit signed integer */
128                floating_point   /* single precision floating point */
129 } data_format;
130
131 typedef enum { rect, polar } phasor_notation;
132
133 /* holds the information required to dissect a single phasor */
134 typedef struct {
135         char          name[CHNAM_LEN + 1];
136         enum { V, A } unit;
137         guint32       conv; /* conversation factor in 10^-5 scale */
138 } phasor_info;
139
140 /* holds the information for an analog value */
141 typedef struct {
142         char    name[CHNAM_LEN + 1];
143         guint32 conv; /* conversation factor, user defined scaling (so its pretty useless) */
144 } analog_info;
145
146 /* holds information required to dissect a single PMU block in a data frame */
147 typedef struct {
148         guint16         id;                  /* identifies source of block     */
149         char            name[CHNAM_LEN + 1]; /* holds STN                      */
150         data_format     format_fr;           /* data format of FREQ and DFREQ  */
151         data_format     format_ph;           /* data format of PHASORS         */
152         data_format     format_an;           /* data format of ANALOG          */
153         phasor_notation phasor_notation;     /* format of the phasors          */
154         guint           fnom;                /* nominal line frequency         */
155         guint           num_dg;              /* number of digital status words */
156         GArray         *phasors;             /* array of phasor_infos          */
157         GArray         *analogs;             /* array of analog_infos          */
158 } config_block;
159
160 /* holds the id the configuration comes from an and
161  * an array of config_block members */
162 typedef struct {
163         guint32  fnum;          /* frame number */
164
165         guint16  id;
166         GArray  *config_blocks; /* Contains a config_block struct for
167                                  * every PMU included in the config frame */
168 } config_frame;
169
170 /* strings for type bits in SYNC */
171 static const value_string typenames[] = {
172         { 0, "Data Frame"            },
173         { 1, "Header Frame"          },
174         { 2, "Configuration Frame 1" },
175         { 3, "Configuration Frame 2" },
176         { 4, "Command Frame"         },
177         { 0, NULL                    }
178 };
179
180 /* strings for version bits in SYNC */
181 static const value_string versionnames[] = {
182         { 1, "IEEE C37.118-2005 initial publication" },
183         { 0, NULL                                    }
184 };
185
186 /* strings for the time quality flags in FRACSEC */
187 static const value_string timequalcodes[] = {
188         { 0xF, "Clock failure, time not reliable"    },
189         { 0xB, "Clock unlocked, time within 10 s"    },
190         { 0xA, "Clock unlocked, time within 1 s"     },
191         { 0x9, "Clock unlocked, time within 10^-1 s" },
192         { 0x8, "Clock unlocked, time within 10^-2 s" },
193         { 0x7, "Clock unlocked, time within 10^-3 s" },
194         { 0x6, "Clock unlocked, time within 10^-4 s" },
195         { 0x5, "Clock unlocked, time within 10^-5 s" },
196         { 0x4, "Clock unlocked, time within 10^-6 s" },
197         { 0x3, "Clock unlocked, time within 10^-7 s" },
198         { 0x2, "Clock unlocked, time within 10^-8 s" },
199         { 0x1, "Clock unlocked, time within 10^-9 s" },
200         { 0x0, "Normal operation, clock locked"      },
201         {  0 , NULL                                  }
202 };
203
204 /* strings for flags in the FORMAT word of a configuration frame */
205 static const true_false_string conf_formatb123names = {
206         "floating point",
207         "16-bit integer"
208 };
209 static const true_false_string conf_formatb0names = {
210         "polar",
211         "rectangular"
212 };
213
214 /* strings to decode ANUNIT in configuration frame */
215 static const range_string conf_anconvnames[] = {
216         {  0,   0, "single point-on-wave" },
217         {  1,   1, "rms of analog input"  },
218         {  2,   2, "peak of input"        },
219         {  3,   4, "undefined"            },
220         {  5,  64, "reserved"             },
221         { 65, 255, "user defined"         },
222         {  0,   0, NULL                   }
223 };
224
225 /* strings for the FNOM field */
226 static const true_false_string conf_fnomnames = {
227         "50Hz",
228         "60Hz"
229 };
230
231 /* strings for flags in the STAT word of a data frame */
232 static const true_false_string data_statb15names = {
233         "Data is invalid",
234         "Data is valid"
235 };
236 static const true_false_string data_statb14names = {
237         "Error",
238         "No error"
239 };
240 static const true_false_string data_statb13names = {
241         "Synchronization lost",
242         "Clock is synchronized"
243 };
244 static const true_false_string data_statb12names = {
245         "By arrival",
246         "By timestamp"
247 };
248 static const true_false_string data_statb11names = {
249         "Trigger detected",
250         "No trigger"
251 };
252 static const true_false_string data_statb10names = {
253         "Within 1 minute",
254         "No"
255 };
256 static const value_string      data_statb05to04names[] = {
257         { 0, "Time locked, best quality" },
258         { 1, "Unlocked for 10s"          },
259         { 2, "Unlocked for 100s"         },
260         { 3, "Unlocked for over 1000s"   },
261         { 0, NULL                        }
262 };
263 static const value_string      data_statb03to00names[] = {
264         { 0x0, "Manual"             },
265         { 0x1, "Magnitude low"      },
266         { 0x2, "Magnitude high"     },
267         { 0x3, "Phase-angel diff"   },
268         { 0x4, "Frequency high/low" },
269         { 0x5, "df/dt high"         },
270         { 0x6, "Reserved"           },
271         { 0x7, "Digital"            },
272         { 0x8, "User defined"       },
273         { 0x9, "User defined"       },
274         { 0xA, "User defined"       },
275         { 0xB, "User defined"       },
276         { 0xC, "User defined"       },
277         { 0xD, "User defined"       },
278         { 0xE, "User defined"       },
279         { 0xF, "User defined"       },
280         {  0 , NULL                 }
281 };
282
283 /* strings to decode the commands */
284 static const value_string command_names[] = {
285         {  0, "unknown command"       },
286         {  1, "data transmission off" },
287         {  2, "data transmission on"  },
288         {  3, "send HDR frame"        },
289         {  4, "send CFG-1 frame"      },
290         {  5, "send CFG-2 frame"      },
291         {  6, "unknown command"       },
292         {  7, "unknown command"       },
293         {  8, "extended frame"        },
294         {  9, "unknown command"       },
295         { 10, "unknown command"       },
296         { 11, "unknown command"       },
297         { 12, "unknown command"       },
298         { 13, "unknown command"       },
299         { 14, "unknown command"       },
300         { 15, "unknown command"       },
301         {  0, NULL                    }
302 };
303
304 /* Dissects a configuration frame (only the most important stuff, tries
305  * to be fast, does no GUI stuff) and returns a pointer to a config_frame
306  * struct that contains all the information from the frame needed to
307  * dissect a DATA frame.
308  *
309  * use 'config_frame_free()' to free the config_frame again
310  */
311 static config_frame* config_frame_fast(tvbuff_t *tvb)
312 {
313         guint16       idcode, num_pmu;
314         gint          offset;
315         config_frame *frame;
316
317         /* get a new frame and initialize it */
318         frame = g_slice_new(config_frame);
319
320         frame->config_blocks = g_array_new(FALSE, TRUE, sizeof(config_block));
321
322         idcode = tvb_get_ntohs(tvb, 4);
323         frame->id       = idcode;
324
325         num_pmu = tvb_get_ntohs(tvb, 18);
326         offset = 20; /* start of repeating blocks */
327
328         while (num_pmu) {
329                 guint16      format_flags;
330                 gint         num_ph,
331                              num_an,
332                              num_dg;
333                 gint         i,
334                              phunit,
335                              anunit,
336                              fnom;
337                 config_block block;
338
339                 /* initialize the block */
340                 block.phasors = g_array_new(FALSE, TRUE, sizeof(phasor_info));
341                 block.analogs = g_array_new(FALSE, TRUE, sizeof(analog_info));
342                 /* copy the station name from the tvb to block, and add NULL byte */
343                 tvb_memcpy(tvb, block.name, offset, CHNAM_LEN); offset += CHNAM_LEN;
344                 block.name[CHNAM_LEN] = '\0';
345
346                 block.id = tvb_get_ntohs(tvb, offset); offset += 2;
347
348                 format_flags          = tvb_get_ntohs(tvb, offset); offset += 2;
349                 block.format_fr       = (format_flags & 0x0008) ? floating_point : integer;
350                 block.format_an       = (format_flags & 0x0004) ? floating_point : integer;
351                 block.format_ph       = (format_flags & 0x0002) ? floating_point : integer;
352                 block.phasor_notation = (format_flags & 0x0001) ? polar          : rect;
353
354                 num_ph = tvb_get_ntohs(tvb, offset); offset += 2;
355                 num_an = tvb_get_ntohs(tvb, offset); offset += 2;
356                 num_dg = tvb_get_ntohs(tvb, offset); offset += 2;
357                 block.num_dg = num_dg;
358
359                 /* the offset of the PHUNIT, ANUNIT, and FNOM blocks */
360                 phunit = offset + (num_ph + num_an + num_dg * CHNAM_LEN) * CHNAM_LEN;
361                 anunit = phunit + num_ph * 4;
362                 fnom   = anunit + num_an * 4 + num_dg * 4;
363
364                 /* read num_ph phasor names and conversation factors */
365                 for (i = 0; i != num_ph; i++) {
366                         phasor_info  pi;
367                         guint32      conv;
368
369                         /* copy the phasor name from the tvb, and add NULL byte */
370                         tvb_memcpy(tvb, pi.name, offset, CHNAM_LEN); offset += CHNAM_LEN;
371                         pi.name[CHNAM_LEN] = '\0';
372
373                         conv = tvb_get_ntohl(tvb, phunit + 4 * i);
374                         pi.unit = conv & 0xFF000000 ? A : V;
375                         pi.conv = conv & 0x00FFFFFF;
376
377                         g_array_append_val(block.phasors, pi);
378                 }
379
380                 /* read num_an analog value names and conversation factors */
381                 for (i = 0; i != num_an; i++) {
382                         analog_info ai;
383                         guint32     conv;
384
385                         /* copy the phasor name from the tvb, and add NULL byte */
386                         tvb_memcpy(tvb, ai.name, offset, CHNAM_LEN); offset += CHNAM_LEN;
387                         ai.name[CHNAM_LEN] = '\0';
388
389                         conv = tvb_get_ntohl(tvb, anunit + 4 * i);
390                         ai.conv = conv;
391
392                         g_array_append_val(block.analogs, ai);
393                 }
394
395                 /* the names for the bits in the digital status words aren't saved,
396                    there is no space to display them in the GUI anyway */
397
398                 /* save FNOM */
399                 block.fnom = tvb_get_ntohs(tvb, fnom) & 0x0001 ? 50 : 60;
400                 offset = fnom + 2;
401
402                 /* skip CFGCNT */
403                 offset += 2;
404
405                 g_array_append_val(frame->config_blocks, block);
406                 num_pmu--;
407         }
408
409         return frame;
410 }
411
412 /* Frees the memory pointed to by 'frame' and all the contained
413  * config_blocks and the data in their GArrays.
414  */
415 static void config_frame_free(config_frame *frame)
416 {
417         int i = frame->config_blocks->len;
418
419         /* free all the config_blocks this frame contains */
420         while (i--) {
421                 config_block *block;
422
423                 block = &g_array_index(frame->config_blocks, config_block, i);
424                 g_array_free(block->phasors, TRUE);
425                 g_array_free(block->analogs, TRUE);
426         }
427
428         /* free the array of config blocks itself */
429         g_array_free(frame->config_blocks, TRUE);
430
431         /* and the config_frame */
432         g_slice_free1(sizeof(config_frame), frame);
433 }
434
435 /* called every time the user loads a capture file or starts to capture */
436 static void synphasor_init(void)
437 {
438         /* free stuff in the list from a previous run */
439         if (config_frame_list) {
440                 g_slist_foreach(config_frame_list, (GFunc) config_frame_free, NULL);
441
442                 g_slist_free(config_frame_list);
443
444                 config_frame_list = NULL;
445         }
446
447 }
448
449 /* the main dissection routine */
450 static void dissect_common(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree);
451
452 /* called for synchrophasors over UDP */
453 static void dissect_udp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
454 {
455         dissect_common(tvb, pinfo, tree);
456 }
457
458 /* callback for 'tcp_dissect_pdus()' to give it the length of the frame */
459 static guint get_pdu_length(packet_info *pinfo _U_, tvbuff_t *tvb, int offset)
460 {
461         return tvb_get_ntohs(tvb, offset + 2);
462 }
463
464 static void dissect_tcp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
465 {
466         tcp_dissect_pdus(tvb, pinfo, tree, TRUE, 4, get_pdu_length, dissect_common);
467 }
468
469 /* Checks the CRC of a synchrophasor frame, 'tvb' has to include the whole
470  * frame, including CRC, the calculated CRC is returned in '*computedcrc'.
471  */
472 static gboolean check_crc(tvbuff_t *tvb, guint16 *computedcrc)
473 {
474         guint16 crc;
475         guint   len = tvb_get_ntohs(tvb, 2);
476
477         crc = tvb_get_ntohs(tvb, len - 2);
478         *computedcrc = crc16_x25_ccitt_tvb(tvb, len - 2);
479
480         if (crc == *computedcrc)
481                 return TRUE;
482
483         return FALSE;
484 }
485
486 /* forward declarations of the subdissectors for the data
487  * in the frame that is not common to all types of frames
488  */
489 static int dissect_config_frame (tvbuff_t *, proto_item *);
490 static int dissect_data_frame   (tvbuff_t *, proto_item *, packet_info *);
491 static int dissect_command_frame(tvbuff_t *, proto_item *, packet_info *);
492 /* to keep 'dissect_common()' shorter */
493 static gint dissect_header(tvbuff_t *, proto_tree *);
494
495 /* Dissects the header (common to all types of frames) and then calls
496  * one of the subdissectors (declared above) for the rest of the frame.
497  */
498 static void dissect_common(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
499 {
500         guint8  frame_type;
501         guint16 crc;
502         guint   tvbsize = tvb_length(tvb);
503
504         /* some heuristics */
505         if (tvbsize < 17                    /* 17 bytes = header frame with only a
506                                                NULL character, useless but valid */
507          || tvb_get_guint8(tvb, 0) != 0xAA) /* every synchrophasor frame starts with 0xAA */
508                 return;
509
510         /* write the protocol name to the info column */
511         if (check_col(pinfo->cinfo, COL_PROTOCOL))
512                 col_set_str(pinfo->cinfo, COL_PROTOCOL, PROTOCOL_SHORT_NAME);
513
514         frame_type = tvb_get_guint8(tvb, 1) >> 4;
515
516         if (check_col(pinfo->cinfo, COL_INFO)) {
517                 col_clear(pinfo->cinfo, COL_INFO); /* clear out stuff in the info column */
518                 col_add_fstr(pinfo->cinfo, COL_INFO, "%s", val_to_str(frame_type, typenames, "invalid packet type"));
519         }
520
521         /* CFG-2 and DATA frames need special treatment during the first run:
522          * For CFG-2 frames, a 'config_frame' struct is created to hold the
523          * information necessary to decode DATA frames. A pointer to this
524          * struct is saved in the conversation and is copied to the
525          * per-packet information if a DATA frame is dissected.
526          */
527         if (!pinfo->fd->flags.visited) {
528                 if (CFG2 == frame_type &&
529                     check_crc(tvb, &crc)) {
530                         conversation_t *conversation;
531
532                         /* fill the config_frame */
533                         config_frame *frame = config_frame_fast(tvb);
534                         frame->fnum = pinfo->fd->num;
535                         /* so we can cleanup later */
536                         config_frame_list = g_slist_append(config_frame_list, frame);
537
538                         /* find a conversation, create a new if no one exists */
539                         conversation = find_or_create_conversation(pinfo);
540
541                         /* remove data from a previous CFG-2 frame, only
542                          * the most recent configuration frame is relevant */
543                         if (conversation_get_proto_data(conversation, proto_synphasor))
544                                 conversation_delete_proto_data(conversation, proto_synphasor);
545
546                         conversation_add_proto_data(conversation, proto_synphasor, frame);
547                 }
548                 else if (DATA == frame_type) {
549                         conversation_t *conversation = find_conversation(pinfo->fd->num,
550                                                                          &pinfo->src, &pinfo->dst,
551                                                                          pinfo->ptype,
552                                                                          pinfo->srcport, pinfo->destport,
553                                                                          0);
554
555                         if (conversation) {
556                                 config_frame *conf = conversation_get_proto_data(conversation, proto_synphasor);
557                                 /* no problem if 'conf' is NULL, the DATA frame dissector checks this again */
558                                 p_add_proto_data(pinfo->fd, proto_synphasor, conf);
559                         }
560                 }
561         } /* if (!visited) */
562
563         if (tree) { /* we are being asked for details */
564                 proto_tree *synphasor_tree = NULL;
565                 proto_item *temp_item      = NULL;
566                 proto_item *sub_item       = NULL;
567
568                 gint     offset;
569                 guint16  framesize;
570                 tvbuff_t *sub_tvb;
571
572                 temp_item = proto_tree_add_item(tree, proto_synphasor, tvb, 0, -1, ENC_NA);
573                 proto_item_append_text(temp_item, ", %s", val_to_str(frame_type, typenames,
574                                                                      ", invalid packet type"));
575
576                 /* synphasor_tree is where from now on all new elements for this protocol get added */
577                 synphasor_tree = proto_item_add_subtree(temp_item, ett_synphasor);
578
579                 framesize = dissect_header(tvb, synphasor_tree);
580                 offset = 14; /* header is 14 bytes long */
581
582                 /* check CRC, call appropriate subdissector for the rest of the frame if CRC is correct*/
583                 sub_item  = proto_tree_add_text(synphasor_tree, tvb, offset     , tvbsize - 16, "Data"     );
584                 temp_item = proto_tree_add_text(synphasor_tree, tvb, tvbsize - 2, 2           , "Checksum:");
585                 if (!check_crc(tvb, &crc)) {
586                         proto_item_append_text(sub_item,  ", not dissected because of wrong checksum");
587                         proto_item_append_text(temp_item, " 0x%04x [incorrect]", crc);
588                 }
589                 else {
590                         /* create a new tvb to pass to the subdissector
591                            '-16': length of header + 2 CRC bytes */
592                         sub_tvb = tvb_new_subset(tvb, offset, tvbsize - 16, framesize - 16);
593
594                         /* call subdissector */
595                         switch (frame_type) {
596                                 case DATA:
597                                         offset += dissect_data_frame(sub_tvb, sub_item, pinfo);
598                                         break;
599                                 case HEADER: /* no further dissection is done/needed */
600                                         proto_item_append_text(sub_item, "Header Frame");
601                                         offset += tvb_length(sub_tvb);
602                                         break;
603                                 case CFG1:
604                                 case CFG2:
605                                         offset += dissect_config_frame(sub_tvb, sub_item);
606                                         break;
607                                 case CMD:
608                                         offset += dissect_command_frame(sub_tvb, sub_item, pinfo);
609                                         break;
610
611                                 default:
612                                         proto_item_append_text(sub_item, " of unknown type");
613                         }
614                         proto_item_append_text(temp_item, " 0x%04x [correct]", crc);
615                 }
616
617                 offset += 2; /* CRC */
618         } /* if (tree) */
619 } /* dissect_synphasor() */
620
621 /* Dissects the common header of frames.
622  *
623  * Returns the framesize, in contrast to most
624  * other helper functions that return the offset.
625  */
626 static gint dissect_header(tvbuff_t *tvb, proto_tree *tree)
627 {
628         proto_tree *temp_tree;
629         proto_item *temp_item;
630
631         gint    offset = 0;
632         guint16 framesize;
633
634         /* SYNC and flags */
635         temp_item = proto_tree_add_item(tree, hf_sync, tvb, offset, 2, ENC_BIG_ENDIAN);
636         temp_tree = proto_item_add_subtree(temp_item, ett_frtype);
637                 proto_tree_add_item(temp_tree, hf_sync_frtype,  tvb, offset, 2, ENC_BIG_ENDIAN);
638                 proto_tree_add_item(temp_tree, hf_sync_version, tvb, offset, 2, ENC_BIG_ENDIAN);
639         offset += 2;
640
641         /* FRAMESIZE */
642         proto_tree_add_item(tree, hf_frsize, tvb, offset, 2, ENC_BIG_ENDIAN);
643         framesize = tvb_get_ntohs(tvb, offset); offset += 2;
644
645         /* IDCODE */
646         proto_tree_add_item(tree, hf_idcode, tvb, offset, 2, ENC_BIG_ENDIAN);
647         offset += 2;
648
649         /* SOC */
650         {
651                 /* can't use 'proto_tree_add_time()' because we need UTC */
652                 char   buf[20];
653                 struct tm* t;
654                 time_t soc = tvb_get_ntohl(tvb, offset);
655                 t = gmtime(&soc);
656                 strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", t);
657                 proto_tree_add_string(tree, hf_soc, tvb, offset, 4, buf);
658                 offset += 4;
659         }
660
661         /* FRACSEC */
662         /* time quality flags */
663         temp_item = proto_tree_add_text(tree, tvb, offset, 1, "Time quality flags");
664         temp_tree = proto_item_add_subtree(temp_item, ett_timequal);
665                 proto_tree_add_item(temp_tree, hf_timeqal_lsdir,         tvb, offset, 1, ENC_BIG_ENDIAN);
666                 proto_tree_add_item(temp_tree, hf_timeqal_lsocc,         tvb, offset, 1, ENC_BIG_ENDIAN);
667                 proto_tree_add_item(temp_tree, hf_timeqal_lspend,        tvb, offset, 1, ENC_BIG_ENDIAN);
668                 proto_tree_add_item(temp_tree, hf_timeqal_timequalindic, tvb, offset, 1, ENC_BIG_ENDIAN);
669         offset += 1;
670
671         proto_tree_add_item(tree, hf_fracsec,  tvb, offset, 3, ENC_BIG_ENDIAN); offset += 3;
672
673         return framesize;
674 }
675
676 /* forward declarations of helper functions for 'dissect_config_frame()' */
677 static gint dissect_CHNAM  (tvbuff_t *tvb, proto_tree *tree, gint offset, gint cnt, char *prefix);
678 static gint dissect_PHUNIT (tvbuff_t *tvb, proto_tree *tree, gint offset, gint cnt);
679 static gint dissect_ANUNIT (tvbuff_t *tvb, proto_tree *tree, gint offset, gint cnt);
680 static gint dissect_DIGUNIT(tvbuff_t *tvb, proto_tree *tree, gint offset, gint cnt);
681
682 /* dissects a configuration frame (type 1 and 2) and adds fields to 'config_item' */
683 static int dissect_config_frame(tvbuff_t *tvb, proto_item *config_item)
684 {
685         proto_tree *config_tree = NULL;
686         proto_item *temp_item   = NULL;
687         proto_tree *temp_tree   = NULL;
688         gint     offset = 0, j;
689         guint16  num_pmu;
690
691         proto_item_set_text   (config_item, "Configuration data");
692         config_tree = proto_item_add_subtree(config_item, ett_conf);
693
694         /* TIME_BASE and NUM_PMU */
695         offset += 1; /* skip the reserved byte */
696         proto_tree_add_item(config_tree, hf_conf_timebase, tvb, offset, 3, ENC_BIG_ENDIAN); offset += 3;
697         proto_tree_add_item(config_tree, hf_conf_numpmu,   tvb, offset, 2, ENC_BIG_ENDIAN);
698         /* add number of included PMUs to the text in the list view  */
699         num_pmu = tvb_get_ntohs(tvb, offset); offset += 2;
700         proto_item_append_text(config_item, ", %"G_GUINT16_FORMAT" PMU(s) included", num_pmu);
701
702         /* dissect the repeating PMU blocks */
703         for (j = 0; j < num_pmu; j++) {
704                 guint16  num_ph, num_an, num_dg;
705                 proto_item *station_item = NULL;
706                 proto_tree *station_tree = NULL;
707                 char *str;
708
709                 gint oldoffset = offset; /* to calculate the length of the whole PMU block later */
710
711                 /* STN with new tree to add the rest of the PMU block */
712                 str = tvb_get_ephemeral_string(tvb, offset, CHNAM_LEN);
713                 station_item = proto_tree_add_text(config_tree, tvb, offset, CHNAM_LEN, "Station #%i: \"%s\"", j + 1, str);
714                 station_tree = proto_item_add_subtree(station_item, ett_conf_station);
715                 offset += CHNAM_LEN;
716
717                 /* IDCODE */
718                 proto_tree_add_item(station_tree, hf_idcode, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2;
719
720                 /* FORMAT */
721                 temp_item = proto_tree_add_text(station_tree, tvb, offset, 2, "Data format in data frame");
722                 temp_tree = proto_item_add_subtree(temp_item, ett_conf_format);
723                         proto_tree_add_item(temp_tree, hf_conf_formatb3, tvb, offset, 2, ENC_BIG_ENDIAN);
724                         proto_tree_add_item(temp_tree, hf_conf_formatb2, tvb, offset, 2, ENC_BIG_ENDIAN);
725                         proto_tree_add_item(temp_tree, hf_conf_formatb1, tvb, offset, 2, ENC_BIG_ENDIAN);
726                         proto_tree_add_item(temp_tree, hf_conf_formatb0, tvb, offset, 2, ENC_BIG_ENDIAN);
727                 offset += 2;
728
729                 /* PHNMR, ANNMR, DGNMR */
730                 num_ph = tvb_get_ntohs(tvb, offset    );
731                 num_an = tvb_get_ntohs(tvb, offset + 2);
732                 num_dg = tvb_get_ntohs(tvb, offset + 4);
733                 proto_tree_add_text(station_tree, tvb, offset    , 2, "Number of phasors: %u",              num_ph);
734                 proto_tree_add_text(station_tree, tvb, offset + 2, 2, "Number of analog values: %u",        num_an);
735                 proto_tree_add_text(station_tree, tvb, offset + 4, 2, "Number of digital status words: %u", num_dg);
736                 offset += 6;
737
738                 /* CHNAM, the channel names */
739                 offset = dissect_CHNAM(tvb, station_tree, offset, num_ph     , "Phasor name"         );
740                 offset = dissect_CHNAM(tvb, station_tree, offset, num_an     , "Analog value"        );
741                 offset = dissect_CHNAM(tvb, station_tree, offset, num_dg * 16, "Digital status label");
742
743                 /* PHUNIT, ANUINT and DIGUNIT */
744                 offset = dissect_PHUNIT (tvb, station_tree, offset, num_ph);
745                 offset = dissect_ANUNIT (tvb, station_tree, offset, num_an);
746                 offset = dissect_DIGUNIT(tvb, station_tree, offset, num_dg);
747
748                 /* FNOM and CFGCNT */
749                 proto_tree_add_item(station_tree, hf_conf_fnom,   tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2;
750                 proto_tree_add_item(station_tree, hf_conf_cfgcnt, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2;
751
752                 /* set the correct length for the "Station :" item */
753                 proto_item_set_len(station_item, offset - oldoffset);
754         } /* for() PMU blocks */
755
756         /* DATA_RATE */
757         {
758                 gint16 tmp = tvb_get_ntohs(tvb, offset);
759                 temp_item  = proto_tree_add_text(config_tree, tvb, offset, 2, "Rate of transmission: "); offset += 2;
760                 if (tmp > 0)
761                         proto_item_append_text(temp_item, "%"G_GINT16_FORMAT" frame(s) per second", tmp);
762                 else
763                         proto_item_append_text(temp_item, "1 frame per %"G_GINT16_FORMAT" second(s)", (gint16)-tmp);
764         }
765
766         return offset;
767 } /* dissect_config_frame() */
768
769 /* forward declarations of helper functions for 'dissect_data_frame()' */
770 static gint dissect_PHASORS(tvbuff_t *tvb, proto_tree *tree, config_block *block, gint offset);
771 static gint dissect_DFREQ  (tvbuff_t *tvb, proto_tree *tree, config_block *block, gint offset);
772 static gint dissect_ANALOG (tvbuff_t *tvb, proto_tree *tree, config_block *block, gint offset);
773 static gint dissect_DIGITAL(tvbuff_t *tvb, proto_tree *tree, config_block *block, gint offset);
774 /* calculates the size (in bytes) of a data frame that the config_block describes */
775 #define BLOCKSIZE(x) (2                                                    /* STAT    */ \
776                    + (x).phasors->len * (integer == (x).format_ph ? 4 : 8) /* PHASORS */ \
777                    +                    (integer == (x).format_fr ? 4 : 8) /* (D)FREQ */ \
778                    + (x).analogs->len * (integer == (x).format_an ? 2 : 4) /* ANALOG  */ \
779                    + (x).num_dg * 2)                                       /* DIGITAL */
780
781 /* Dissects a data frame */
782 static int dissect_data_frame(tvbuff_t    *tvb,
783                               proto_item  *data_item, /* all items are placed beneath this item   */
784                               packet_info *pinfo)     /* used to find the data from a CFG-2 frame */
785 {
786         proto_tree   *data_tree  = NULL;
787         gint          offset     = 0;
788         guint         i;
789         config_frame *conf;
790
791         proto_item_set_text(data_item, "Measurement data");
792         data_tree = proto_item_add_subtree(data_item, ett_data);
793
794         /* search for configuration information to dissect the frame */
795         {
796                 gboolean config_found = FALSE;
797                 conf = p_get_proto_data(pinfo->fd, proto_synphasor);
798
799                 if (conf) {
800                         /* check if the size of the current frame is the
801                            size of the frame the config_frame describes */
802                         size_t reported_size = 0;
803                         for (i = 0; i < conf->config_blocks->len; i++) {
804                                 config_block *block = &g_array_index(conf->config_blocks, config_block, i);
805                                 reported_size += BLOCKSIZE(*block);
806                         }
807
808                         if (tvb_length(tvb) == reported_size) {
809                                 proto_item_append_text(data_item, ", using frame number %"G_GUINT32_FORMAT" as configuration frame",
810                                                        conf->fnum);
811                                 config_found = TRUE;
812                         }
813                 }
814
815                 if (!config_found) {
816                         proto_item_append_text(data_item, ", no configuration frame found");
817                         return 0;
818                 }
819         }
820
821         /* dissect a PMU block for every config_block in the frame */
822         for (i = 0; i < conf->config_blocks->len; i++) {
823                 config_block *block = &g_array_index(conf->config_blocks, config_block, i);
824
825                 proto_item *block_item = proto_tree_add_text(data_tree, tvb, offset, BLOCKSIZE(*block),
826                                                  "Station: \"%s\"", block->name);
827                 proto_tree *block_tree = proto_item_add_subtree(block_item, ett_data_block);
828
829                 /* STAT */
830                 proto_item *temp_item = proto_tree_add_text(block_tree, tvb, offset, 2, "Flags");
831                 proto_tree *temp_tree = proto_item_add_subtree(temp_item, ett_data_stat);
832                         proto_tree_add_item(temp_tree, hf_data_statb15,     tvb, offset, 2, ENC_BIG_ENDIAN);
833                         proto_tree_add_item(temp_tree, hf_data_statb14,     tvb, offset, 2, ENC_BIG_ENDIAN);
834                         proto_tree_add_item(temp_tree, hf_data_statb13,     tvb, offset, 2, ENC_BIG_ENDIAN);
835                         proto_tree_add_item(temp_tree, hf_data_statb12,     tvb, offset, 2, ENC_BIG_ENDIAN);
836                         proto_tree_add_item(temp_tree, hf_data_statb11,     tvb, offset, 2, ENC_BIG_ENDIAN);
837                         proto_tree_add_item(temp_tree, hf_data_statb10,     tvb, offset, 2, ENC_BIG_ENDIAN);
838                         proto_tree_add_item(temp_tree, hf_data_statb05to04, tvb, offset, 2, ENC_BIG_ENDIAN);
839                         proto_tree_add_item(temp_tree, hf_data_statb03to00, tvb, offset, 2, ENC_BIG_ENDIAN);
840                 offset += 2;
841
842                 /* PHASORS, (D)FREQ, ANALOG, and DIGITAL */
843                 offset = dissect_PHASORS(tvb, block_item, block, offset);
844                 offset = dissect_DFREQ  (tvb, block_item, block, offset);
845                 offset = dissect_ANALOG (tvb, block_item, block, offset);
846                 offset = dissect_DIGITAL(tvb, block_item, block, offset);
847         }
848         return offset;
849 } /* dissect_data_frame() */
850
851 /* Dissects a command frame and adds fields to config_item.
852  *
853  * 'pinfo' is used to add the type of command
854  * to the INFO column in the packet list.
855  */
856 static int dissect_command_frame(tvbuff_t    *tvb,
857                                  proto_item  *command_item,
858                                  packet_info *pinfo)
859 {
860         proto_tree *command_tree  = NULL;
861         guint       tvbsize       = tvb_length(tvb);
862
863         proto_item_set_text(command_item, "Command data");
864         command_tree = proto_item_add_subtree(command_item, ett_command);
865
866         /* CMD */
867         proto_tree_add_item(command_tree, hf_command, tvb, 0, 2, ENC_BIG_ENDIAN);
868         if (check_col(pinfo->cinfo, COL_INFO)) {
869                 const char *s = val_to_str(tvb_get_ntohs(tvb, 0), command_names, "invalid command");
870                 col_append_str(pinfo->cinfo, COL_INFO, ", ");
871                 col_append_str(pinfo->cinfo, COL_INFO, s);
872         }
873
874         if (tvbsize > 2) {
875                 if (tvb_get_ntohs(tvb, 0) == 0x0008) {
876                         /* Command: Extended Frame, the extra data is ok */
877                                 proto_item* i = proto_tree_add_text(command_tree, tvb, 2, tvbsize - 2, "Extended frame data");
878                                 if (tvbsize % 2)
879                                         proto_item_append_text(i, ", but size not multiple of 16-bit word");
880                 }
881                 else
882                         proto_tree_add_text(command_tree, tvb, 2, tvbsize - 2, "Unknown data");
883         }
884
885         return tvbsize;
886 } /* dissect_command_frame() */
887
888 /****************************************************************/
889 /* after this line: helper functions for 'dissect_data_frame()' */
890 /****************************************************************/
891
892 /* Dissects a single phasor for 'dissect_PHASORS()' */
893 static int dissect_single_phasor(tvbuff_t *tvb, int offset,
894                                         double* mag, double* phase, /* returns the resulting values here */
895                                         data_format     format,     /* information needed to... */
896                                         phasor_notation notation)   /*   ...dissect the phasor  */
897 {
898         if (floating_point == format) {
899                 if (polar == notation) {
900                         /* float, polar */
901                         *mag   = tvb_get_ntohieee_float(tvb, offset    );
902                         *phase = tvb_get_ntohieee_float(tvb, offset + 4);
903                 }
904                 else {
905                         /* float, rect */
906                         gfloat real, imag;
907                         real = tvb_get_ntohieee_float(tvb, offset    );
908                         imag = tvb_get_ntohieee_float(tvb, offset + 4);
909
910                         *mag   = sqrt(pow(real, 2) + pow(imag, 2));
911                         *phase = atan2(imag, real);
912                 }
913         }
914         else {
915                 if (polar == notation) {
916                         /* int, polar */
917                         *mag    = (guint16)tvb_get_ntohs(tvb, offset    );
918                         *phase  = (gint16) tvb_get_ntohs(tvb, offset + 2);
919                         *phase /= 10000.0; /* angle is in radians*10^4 */
920                 }
921                 else {
922                         /* int, rect */
923                         gint16 real, imag;
924                         real = tvb_get_ntohs(tvb, offset    );
925                         imag = tvb_get_ntohs(tvb, offset + 2);
926
927                         *mag   = sqrt(pow(real, 2) + pow(imag, 2));
928                         *phase = atan2(imag, real);
929                 }
930         }
931
932         return floating_point == format ? 8 : 4;
933 }
934
935 /* used by 'dissect_data_frame()' to dissect the PHASORS field */
936 static gint dissect_PHASORS(tvbuff_t *tvb, proto_tree *tree, config_block *block, gint offset)
937 {
938         proto_item *temp_item   = NULL;
939         proto_tree *phasor_tree = NULL;
940         guint       length;
941         gint        j,
942                     cnt = block->phasors->len; /* number of phasors to dissect */
943
944         if (0 == cnt)
945                 return offset;
946
947         length      = block->phasors->len * (floating_point == block->format_ph ? 8 : 4);
948         temp_item   = proto_tree_add_text(tree, tvb, offset, length, "Phasors (%u)", cnt);
949         phasor_tree = proto_item_add_subtree(temp_item, ett_data_phasors);
950
951         /* dissect a phasor for every phasor_info saved in the config_block */
952         for (j = 0; j < cnt; j++) {
953                 double       mag, phase;
954                 phasor_info *pi;
955
956                 pi = &g_array_index(block->phasors, phasor_info, j);
957                 temp_item = proto_tree_add_text(phasor_tree, tvb, offset,
958                                                 floating_point == block->format_ph ? 8 : 4,
959                                                 "Phasor #%u: \"%s\"", j + 1, pi->name);
960
961                 offset += dissect_single_phasor(tvb, offset,
962                                                 &mag, &phase,
963                                                 block->format_ph,
964                                                 block->phasor_notation);
965
966                 /* for values in integer format, apply conversation factor */
967                 if (integer == block->format_ph)
968                         mag = (mag * pi->conv) * 0.00001;
969
970                 #define ANGLE  "/_"
971                 #define DEGREE "\xC2\xB0" /* DEGREE signs in UTF-8 */
972
973                 proto_item_append_text(temp_item, ", %10.2f%c" ANGLE "%7.2f" DEGREE,
974                                                   mag,
975                                                   V == pi->unit ? 'V' : 'A',
976                                                   phase *180.0/G_PI);
977                 #undef ANGLE
978                 #undef DEGREE
979         }
980         return offset;
981 }
982
983 /* used by 'dissect_data_frame()' to dissect the FREQ and DFREQ fields */
984 static gint dissect_DFREQ(tvbuff_t *tvb, proto_tree *tree, config_block *block, gint offset)
985 {
986         if (floating_point == block->format_fr) {
987                 gfloat tmp;
988
989                 tmp = tvb_get_ntohieee_float(tvb, offset);
990                 proto_tree_add_text(tree, tvb, offset, 4, "Actual frequency value: %fHz", tmp); offset += 4;
991
992                 /* The standard doesn't clearly say how to interpret this value, but
993                  * http://www.pes-psrc.org/h/C37_118_H11_FAQ_Jan2008.pdf provides further information.
994                  * --> no scaling factor is applied to DFREQ
995                  */
996                 tmp = tvb_get_ntohieee_float(tvb, offset);
997                 proto_tree_add_text(tree, tvb, offset, 4, "Rate of change of frequency: %fHz/s", tmp); offset += 4;
998         }
999         else {
1000                 gint16 tmp;
1001
1002                 tmp = tvb_get_ntohs(tvb, offset);
1003                 proto_tree_add_text(tree, tvb, offset, 2,
1004                                     "Frequency deviation from nominal: %" G_GINT16_FORMAT "mHz (actual frequency: %.3fHz)",
1005                                     tmp, block->fnom + (tmp / 1000.0));
1006                 offset += 2;
1007
1008                 tmp = tvb_get_ntohs(tvb, offset);
1009                 proto_tree_add_text(tree, tvb, offset, 2, "Rate of change of frequency: %.3fHz/s", tmp / 100.0); offset += 2;
1010         }
1011         return offset;
1012 }
1013
1014 /* used by 'dissect_data_frame()' to dissect the ANALOG field */
1015 static gint dissect_ANALOG(tvbuff_t *tvb, proto_tree *tree, config_block *block, gint offset)
1016 {
1017         proto_tree *analog_tree = NULL;
1018         proto_item *temp_item   = NULL;
1019         guint       length;
1020         gint        j,
1021                     cnt = block->analogs->len; /* number of analog values to dissect */
1022
1023         if (0 == cnt)
1024                 return offset;
1025
1026         length      = block->analogs->len * (floating_point == block->format_an ? 4 : 2);
1027         temp_item   = proto_tree_add_text(tree, tvb, offset, length, "Analog values (%u)", cnt);
1028
1029         analog_tree = proto_item_add_subtree(temp_item, ett_data_analog);
1030
1031         for (j = 0; j < cnt; j++) {
1032                 analog_info *ai = &g_array_index(block->analogs, analog_info, j);
1033
1034                 temp_item = proto_tree_add_text(analog_tree, tvb, offset,
1035                                                 floating_point == block->format_an ? 4 : 2,
1036                                                 "Analog value #%u: \"%s\"", j + 1, ai->name);
1037
1038                 if (floating_point == block->format_an) {
1039                         gfloat tmp = tvb_get_ntohieee_float(tvb, offset); offset += 4;
1040                         proto_item_append_text(temp_item, ", %.3f", tmp);
1041                 }
1042                 else {
1043                         /* the "standard" doesn't say if this is signed or unsigned,
1044                          * so I just use gint16, the scaling of the conversation factor
1045                          * is also "user defined", so I just write it after the analog value */
1046                         gint16 tmp = tvb_get_ntohs(tvb, offset); offset += 2;
1047                         proto_item_append_text(temp_item, ", %" G_GINT16_FORMAT " (conversation factor: %#06x)",
1048                                                tmp, ai->conv);
1049                 }
1050         }
1051         return offset;
1052 }
1053
1054 /* used by 'dissect_data_frame()' to dissect the DIGITAL field */
1055 static gint dissect_DIGITAL(tvbuff_t *tvb, proto_tree *tree, config_block *block, gint offset)
1056 {
1057         proto_item *digital_item = NULL;
1058         gint        j,
1059                     cnt = block->num_dg; /* number of digital status words to dissect */
1060
1061         if (0 == cnt)
1062                 return offset;
1063
1064         digital_item = proto_tree_add_text(tree, tvb, offset, cnt * 2, "Digital status words (%u)", cnt);
1065         tree         = proto_item_add_subtree(digital_item, ett_data_digital);
1066
1067         for (j = 0; j < cnt; j++) {
1068                 guint16 tmp = tvb_get_ntohs(tvb, offset);
1069                 proto_tree_add_text(tree, tvb, offset, 2, "Digital status word #%u: 0x%04x", j + 1, tmp);
1070                 offset += 2;
1071         }
1072         return offset;
1073 }
1074
1075 /*******************************************************************/
1076 /* after this line:  helper functions for 'dissect_config_frame()' */
1077 /*******************************************************************/
1078
1079 /* used by 'dissect_config_frame()' to dissect the PHUNIT field */
1080 static gint dissect_PHUNIT(tvbuff_t *tvb, proto_tree *tree, gint offset, gint cnt)
1081 {
1082         proto_item *temp_item = NULL;
1083         proto_tree *temp_tree = NULL;
1084         int i;
1085
1086         if (0 == cnt)
1087                 return offset;
1088
1089         temp_item = proto_tree_add_text(tree, tvb, offset, 4 * cnt, "Phasor conversation factors (%u)", cnt);
1090         temp_tree = proto_item_add_subtree(temp_item, ett_conf_phconv);
1091
1092         /* Conversion factor for phasor channels. Four bytes for each phasor.
1093          * MSB:           0 = voltage, 1 = current
1094          * Lower 3 Bytes: unsigned 24-bit word in 10^-5 V or A per bit to scale the phasor value
1095          */
1096         for (i = 0; i < cnt; i++) {
1097                 guint32 tmp = tvb_get_ntohl(tvb, offset);
1098                 proto_tree_add_text(temp_tree, tvb, offset, 4,
1099                                     "#%u factor: %u * 10^-5, unit: %s",
1100                                     i + 1,
1101                                     tmp & 0x00FFFFFF,
1102                                     tmp & 0xFF000000 ? "Ampere" : "Volt");
1103                 offset += 4;
1104         }
1105
1106         return offset;
1107 }
1108
1109 /* used by 'dissect_config_frame()' to dissect the ANUNIT field */
1110 static gint dissect_ANUNIT(tvbuff_t *tvb, proto_tree *tree, gint offset, gint cnt)
1111 {
1112         proto_item *temp_item = NULL;
1113         proto_tree *temp_tree = NULL;
1114         int i;
1115
1116         if (0 == cnt)
1117                 return offset;
1118
1119         temp_item = proto_tree_add_text(tree, tvb, offset, 4 * cnt, "Analog values conversation factors (%u)", cnt);
1120         temp_tree = proto_item_add_subtree(temp_item, ett_conf_anconv);
1121
1122         /* Conversation factor for analog channels. Four bytes for each analog value.
1123          * MSB: see 'synphasor_conf_anconvnames' in 'synphasor_strings.c'
1124          * Lower 3 Bytes: signed 24-bit word, user-defined scaling
1125          */
1126         for (i = 0; i < cnt; i++) {
1127                 gint32 tmp = tvb_get_ntohl(tvb, offset);
1128                 temp_item = proto_tree_add_text(temp_tree, tvb, offset, 4,
1129                                                 "Factor for analog value #%i: %s",
1130                                                 i + 1,
1131                                                 match_strrval((tmp >> 24) & 0x000000FF, conf_anconvnames));
1132
1133                         tmp &= 0x00FFFFFF;
1134                 if (    tmp &  0x00800000) /* sign bit set */
1135                         tmp |= 0xFF000000;
1136
1137                 proto_item_append_text(temp_item, ", value: %" G_GINT32_FORMAT, tmp);
1138
1139                 offset += 4;
1140         }
1141
1142         return offset;
1143 }
1144
1145 /* used by 'dissect_config_frame()' to dissect the DIGUNIT field */
1146 static gint dissect_DIGUNIT(tvbuff_t *tvb, proto_tree *tree, gint offset, gint cnt)
1147 {
1148         proto_item *temp_item = NULL;
1149         proto_tree *temp_tree = NULL;
1150         int i;
1151
1152         if (0 == cnt)
1153                 return offset;
1154
1155         temp_item = proto_tree_add_text(tree, tvb, offset, 4 * cnt, "Masks for digital status words (%u)", cnt);
1156         temp_tree = proto_item_add_subtree(temp_item, ett_conf_dgmask);
1157
1158         /* Mask words for digital status words. Two 16-bit words for each digital word. The first
1159          * inidcates the normal status of the inputs, the second indicated the valid bits in
1160          * the status word
1161          */
1162         for (i = 0; i < cnt; i++) {
1163                 guint32 tmp = tvb_get_ntohl(tvb, offset);
1164
1165                 temp_item = proto_tree_add_text(temp_tree, tvb, offset, 4, "Mask for status word #%u: ", i + 1);
1166                 proto_item_append_text(temp_item, "normal state: 0x%04"G_GINT16_MODIFIER"x", (guint16)((tmp & 0xFFFF0000) >> 16));
1167                 proto_item_append_text(temp_item, ", valid bits: 0x%04"G_GINT16_MODIFIER"x", (guint16)( tmp & 0x0000FFFF));
1168
1169                 offset += 4;
1170         }
1171
1172         return offset;
1173 }
1174
1175 /* used by 'dissect_config_frame()' to dissect the "channel name"-fields */
1176 static gint dissect_CHNAM(tvbuff_t *tvb, proto_tree *tree, gint offset, gint cnt, char *prefix)
1177 {
1178         proto_item *temp_item = NULL;
1179         proto_tree *temp_tree = NULL;
1180         int i;
1181
1182         if (0 == cnt)
1183                 return offset;
1184
1185         temp_item = proto_tree_add_text(tree, tvb, offset, CHNAM_LEN * cnt, "%ss (%u)", prefix, cnt);
1186         temp_tree = proto_item_add_subtree(temp_item, ett_conf_phnam);
1187
1188         /* dissect the 'cnt' channel names */
1189         for (i = 0; i < cnt; i++) {
1190                 char *str;
1191                 str = tvb_get_ephemeral_string(tvb, offset, CHNAM_LEN);
1192                 proto_tree_add_text(temp_tree, tvb, offset, CHNAM_LEN,
1193                                     "%s #%i: \"%s\"", prefix, i+1, str);
1194                 offset += CHNAM_LEN;
1195         }
1196
1197         return offset;
1198 }
1199
1200 void proto_register_synphasor(void)
1201 {
1202         static hf_register_info hf[] = {
1203                 /* Sync word */
1204                 { &hf_sync,
1205                 { "Synchronization word", PROTOCOL_ABBREV ".sync", FT_UINT16, BASE_HEX,
1206                   NULL, 0x0, NULL, HFILL }},
1207                         /* Flags in the Sync word */
1208                         { &hf_sync_frtype,
1209                         { "Frame Type", PROTOCOL_ABBREV ".frtype", FT_UINT16, BASE_HEX,
1210                           VALS(typenames), 0x0070, NULL, HFILL }},
1211
1212                         { &hf_sync_version,
1213                         { "Version",    PROTOCOL_ABBREV ".version", FT_UINT16, BASE_DEC,
1214                           VALS(versionnames), 0x000F, NULL, HFILL }},
1215
1216                 { &hf_frsize,
1217                 { "Framesize", PROTOCOL_ABBREV ".frsize", FT_UINT16, BASE_DEC,
1218                   NULL, 0x0, NULL, HFILL }},
1219
1220                 { &hf_idcode,
1221                 { "PMU/DC ID number", PROTOCOL_ABBREV ".idcode", FT_UINT16, BASE_DEC,
1222                   NULL, 0x0, NULL, HFILL }},
1223
1224                 { &hf_soc,
1225                 { "SOC time stamp (UTC)", PROTOCOL_ABBREV ".soc", FT_STRINGZ, BASE_NONE,
1226                   NULL, 0x0, NULL, HFILL }},
1227
1228                 /* Time quality flags in fracsec */
1229                 { &hf_timeqal_lsdir,
1230                 { "Leap second direction", PROTOCOL_ABBREV ".timeqal.lsdir", FT_BOOLEAN, 8,
1231                   NULL, 0x40, NULL, HFILL }},
1232
1233                 { &hf_timeqal_lsocc,
1234                 { "Leap second occurred", PROTOCOL_ABBREV ".timeqal.lsocc", FT_BOOLEAN, 8,
1235                   NULL, 0x20, NULL, HFILL }},
1236
1237                 { &hf_timeqal_lspend,
1238                 { "Leap second pending", PROTOCOL_ABBREV ".timeqal.lspend", FT_BOOLEAN, 8,
1239                   NULL, 0x10, NULL, HFILL }},
1240
1241                 { &hf_timeqal_timequalindic,
1242                 { "Time Quality indicator code", PROTOCOL_ABBREV ".timeqal.timequalindic", FT_UINT8, BASE_HEX,
1243                   VALS(timequalcodes), 0x0F, NULL, HFILL }},
1244
1245                 /* Fraction of second */
1246                 { &hf_fracsec,
1247                 { "Fraction of second (raw)", PROTOCOL_ABBREV ".fracsec", FT_UINT24, BASE_DEC,
1248                   NULL, 0x0, NULL, HFILL }},
1249
1250         /* Data types for configuration frames */
1251                 { &hf_conf_timebase,
1252                 { "Resolution of fractional second time stamp", PROTOCOL_ABBREV ".conf.timebase", FT_UINT24, BASE_DEC,
1253                   NULL, 0x0, NULL, HFILL }},
1254
1255                 { &hf_conf_numpmu,
1256                 { "Number of PMU blocks included in the frame", PROTOCOL_ABBREV ".conf.numpmu", FT_UINT16, BASE_DEC,
1257                   NULL, 0x0, NULL, HFILL }},
1258
1259                 /* Bits in the FORMAT word */
1260                 { &hf_conf_formatb3,
1261                 { "FREQ/DFREQ format", PROTOCOL_ABBREV ".conf.dfreq_format", FT_BOOLEAN, 16,
1262                   TFS(&conf_formatb123names), 0x8, NULL, HFILL }},
1263
1264                 { &hf_conf_formatb2,
1265                 { "Analog values format", PROTOCOL_ABBREV ".conf.analog_format", FT_BOOLEAN, 16,
1266                   TFS(&conf_formatb123names), 0x4, NULL, HFILL }},
1267
1268                 { &hf_conf_formatb1,
1269                 { "Phasor format", PROTOCOL_ABBREV ".conf.phasor_format", FT_BOOLEAN, 16,
1270                   TFS(&conf_formatb123names), 0x2, NULL, HFILL }},
1271
1272                 { &hf_conf_formatb0,
1273                 { "Phasor notation", PROTOCOL_ABBREV ".conf.phasor_notation", FT_BOOLEAN, 16,
1274                   TFS(&conf_formatb0names), 0x1, NULL, HFILL }},
1275
1276                 { &hf_conf_fnom,
1277                 { "Nominal line freqency", PROTOCOL_ABBREV ".conf.fnom", FT_BOOLEAN, 16,
1278                   TFS(&conf_fnomnames), 0x0001, NULL, HFILL }},
1279
1280                 { &hf_conf_cfgcnt,
1281                 { "Configuration change count", PROTOCOL_ABBREV ".conf.cfgcnt", FT_UINT16, BASE_DEC,
1282                   NULL, 0, NULL, HFILL }},
1283
1284         /* Data types for data frames */
1285                 /* Flags in the STAT word */
1286                 { &hf_data_statb15,
1287                 { "Data valid", PROTOCOL_ABBREV ".data.valid", FT_BOOLEAN, 16,
1288                   TFS(&data_statb15names), 0x8000, NULL, HFILL }},
1289
1290                 { &hf_data_statb14,
1291                 { "PMU error", PROTOCOL_ABBREV ".data.PMUerror", FT_BOOLEAN, 16,
1292                   TFS(&data_statb14names), 0x4000, NULL, HFILL }},
1293
1294                 { &hf_data_statb13,
1295                 { "Time synchronized", PROTOCOL_ABBREV ".data.sync", FT_BOOLEAN, 16,
1296                   TFS(&data_statb13names), 0x2000, NULL, HFILL }},
1297
1298                 { &hf_data_statb12,
1299                 { "Data sorting", PROTOCOL_ABBREV ".data.sorting", FT_BOOLEAN, 16,
1300                   TFS(&data_statb12names), 0x1000, NULL, HFILL }},
1301
1302                 { &hf_data_statb11,
1303                 { "Trigger detected", PROTOCOL_ABBREV ".data.trigger", FT_BOOLEAN, 16,
1304                   TFS(&data_statb11names), 0x0800, NULL, HFILL }},
1305
1306                 { &hf_data_statb10,
1307                 { "Configuration changed", PROTOCOL_ABBREV ".data.CFGchange", FT_BOOLEAN, 16,
1308                   TFS(&data_statb10names), 0x0400, NULL, HFILL }},
1309
1310                 { &hf_data_statb05to04,
1311                 { "Unlocked time", PROTOCOL_ABBREV  ".data.t_unlock", FT_UINT16, BASE_HEX,
1312                   VALS(data_statb05to04names), 0x0030, NULL, HFILL }},
1313
1314                 { &hf_data_statb03to00,
1315                 { "Trigger reason", PROTOCOL_ABBREV  ".data.trigger_reason", FT_UINT16, BASE_HEX,
1316                   VALS(data_statb03to00names), 0x000F, NULL, HFILL }},
1317
1318         /* Data type for command frame */
1319                 { &hf_command,
1320                 { "Command", PROTOCOL_ABBREV ".command", FT_UINT16, BASE_HEX,
1321                   VALS(command_names), 0x000F, NULL, HFILL }}
1322         };
1323
1324         /* protocol subtree array */
1325         static gint *ett[] = {
1326                 &ett_synphasor,
1327                 &ett_frtype,
1328                 &ett_timequal,
1329                 &ett_conf,
1330                 &ett_conf_station,
1331                 &ett_conf_format,
1332                 &ett_conf_phnam,
1333                 &ett_conf_annam,
1334                 &ett_conf_dgnam,
1335                 &ett_conf_phconv,
1336                 &ett_conf_anconv,
1337                 &ett_conf_dgmask,
1338                 &ett_data,
1339                 &ett_data_block,
1340                 &ett_data_stat,
1341                 &ett_data_phasors,
1342                 &ett_data_analog,
1343                 &ett_data_digital,
1344                 &ett_command
1345         };
1346
1347         module_t *synphasor_module;
1348
1349         /* register protocol */
1350         proto_synphasor = proto_register_protocol(PROTOCOL_NAME,
1351                                                   PROTOCOL_SHORT_NAME,
1352                                                   PROTOCOL_ABBREV);
1353
1354         proto_register_field_array(proto_synphasor, hf, array_length(hf));
1355         proto_register_subtree_array(ett, array_length(ett));
1356
1357         /* register preferences */
1358         synphasor_module = prefs_register_protocol(proto_synphasor, proto_reg_handoff_synphasor);
1359
1360         /* the port numbers of the lower level protocols */
1361         prefs_register_uint_preference(synphasor_module, "udp_port", "Synchrophasor UDP port",
1362                                        "Set the port number for synchrophasor frames over UDP" \
1363                                        "(if other than the default of 4713)",
1364                                        10, &global_pref_udp_port);
1365         prefs_register_uint_preference(synphasor_module, "tcp_port", "Synchrophasor TCP port",
1366                                        "Set the port number for synchrophasor frames over TCP" \
1367                                        "(if other than the default of 4712)",
1368                                        10, &global_pref_tcp_port);
1369
1370         /* register the initalization routine */
1371         register_init_routine(&synphasor_init);
1372 } /* proto_register_synphasor() */
1373
1374 /* called at startup and when the preferences change */
1375 void proto_reg_handoff_synphasor(void)
1376 {
1377         static gboolean           initialized = FALSE;
1378         static dissector_handle_t synphasor_udp_handle;
1379         static dissector_handle_t synphasor_tcp_handle;
1380         static guint              current_udp_port;
1381         static guint              current_tcp_port;
1382
1383         if (!initialized) {
1384                 synphasor_udp_handle = create_dissector_handle(dissect_udp, proto_synphasor);
1385                 synphasor_tcp_handle = create_dissector_handle(dissect_tcp, proto_synphasor);
1386
1387                 initialized = TRUE;
1388         }
1389         else {
1390                 /* update preferences */
1391                 dissector_delete_uint("udp.port", current_udp_port, synphasor_udp_handle);
1392                 dissector_delete_uint("tcp.port", current_tcp_port, synphasor_tcp_handle);
1393         }
1394
1395         current_udp_port = global_pref_udp_port;
1396         current_tcp_port = global_pref_tcp_port;
1397
1398         dissector_add_uint("udp.port", current_udp_port, synphasor_udp_handle);
1399         dissector_add_uint("tcp.port", current_tcp_port, synphasor_tcp_handle);
1400 } /* proto_reg_handoff_synphasor() */