-
Notifications
You must be signed in to change notification settings - Fork 4
/
publish_data.go
421 lines (380 loc) · 14 KB
/
publish_data.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
package dastard
import (
"bytes"
"fmt"
"time"
"github.com/usnistgov/dastard/getbytes"
"github.com/usnistgov/dastard/ljh"
"github.com/usnistgov/dastard/off"
"gonum.org/v1/gonum/mat"
"github.com/pebbe/zmq4"
)
// DataPublisher contains many optional methods for publishing data, any methods that are non-nil will be used
// in each call to PublishData
type DataPublisher struct {
PubRecordsChan chan []*DataRecord
PubSummariesChan chan []*DataRecord
LJH22 *ljh.Writer
LJH3 *ljh.Writer3
OFF *off.Writer
WritingPaused bool
numberWritten int // integrates up the total number written, reset any time writing starts or stops
}
// SetPause changes the paused state to the given value of pause
func (dp *DataPublisher) SetPause(pause bool) {
dp.WritingPaused = pause
dp.Flush()
}
// Flush calls Flush for each writer that has a Flush command (LJH22, LJH3, OFF)
func (dp *DataPublisher) Flush() {
if dp.HasLJH22() {
dp.LJH22.Flush()
}
if dp.HasLJH3() {
dp.LJH3.Flush()
}
if dp.HasOFF() {
dp.OFF.Flush()
}
}
// SetOFF adds an OFF writer to dp, the .file attribute is nil, and will be instantiated upon next call to dp.WriteRecord
func (dp *DataPublisher) SetOFF(ChannelIndex int, Presamples int, Samples int, FramesPerSample int,
Timebase float64, TimestampOffset time.Time,
NumberOfRows, NumberOfColumns, NumberOfChans, SubframeDivisions, rowNum, colNum, SubframeOffset int,
FileName, sourceName, chanName string, ChannelNumberMatchingName int,
Projectors *mat.Dense, Basis *mat.Dense, ModelDescription string, pixel Pixel) {
ReadoutInfo := off.TimeDivisionMultiplexingInfo{
NumberOfRows: NumberOfRows,
NumberOfColumns: NumberOfColumns,
NumberOfChans: NumberOfChans,
SubframeDivisions: SubframeDivisions,
ColumnNum: colNum,
RowNum: rowNum,
SubframeOffset: SubframeOffset}
PixelInfo := off.PixelInfo{XPosition: pixel.X, YPosition: pixel.Y, Name: pixel.Name}
w := off.NewWriter(FileName, ChannelIndex, chanName, ChannelNumberMatchingName, Presamples, Samples, Timebase,
Projectors, Basis, ModelDescription, Build.Version, Build.Githash, sourceName, ReadoutInfo, PixelInfo)
dp.OFF = w
dp.numberWritten = 0
}
// HasOFF returns true if OFF is non-nil, eg if writing to OFF is occuring
func (dp *DataPublisher) HasOFF() bool {
return dp.OFF != nil
}
// RemoveOFF closes any existing OFF file and assign .OFF=nil
func (dp *DataPublisher) RemoveOFF() {
if dp.OFF != nil {
dp.OFF.Close()
}
dp.OFF = nil
dp.numberWritten = 0
}
// SetLJH3 adds an LJH3 writer to dp, the .file attribute is nil, and will be instantiated upon next call to dp.WriteRecord
func (dp *DataPublisher) SetLJH3(ChannelIndex int, Timebase float64,
NumberOfRows, NumberOfColumns, SubframeDivisions, SubframeOffset int,
FileName string) {
w := ljh.Writer3{
ChannelIndex: ChannelIndex,
Timebase: Timebase,
NumberOfRows: NumberOfRows,
NumberOfColumns: NumberOfColumns,
SubframeDivisions: SubframeDivisions,
SubframeOffset: SubframeOffset,
FileName: FileName,
}
dp.LJH3 = &w
dp.WritingPaused = false
dp.numberWritten = 0
}
// HasLJH3 returns true if LJH3 is non-nil, eg if writing to LJH3 is occuring
func (dp *DataPublisher) HasLJH3() bool {
return dp.LJH3 != nil
}
// RemoveLJH3 closes existing LJH3 file and assign .LJH3=nil
func (dp *DataPublisher) RemoveLJH3() {
if dp.LJH3 != nil {
dp.LJH3.Close()
}
dp.LJH3 = nil
dp.numberWritten = 0
}
// SetLJH22 adds an LJH22 writer to dp, the .file attribute is nil, and will be instantiated upon next call to dp.WriteRecord
func (dp *DataPublisher) SetLJH22(ChannelIndex int, Presamples int, Samples int, FramesPerSample int,
Timebase float64, TimestampOffset time.Time,
NumberOfRows, NumberOfColumns, NumberOfChans, SubframeDivisions, rowNum, colNum, SubframeOffset int,
FileName, sourceName, chanName string, ChannelNumberMatchingName int, pixel Pixel) {
w := ljh.Writer{ChannelIndex: ChannelIndex,
Presamples: Presamples,
Samples: Samples,
FramesPerSample: FramesPerSample,
Timebase: Timebase,
TimestampOffset: TimestampOffset,
NumberOfRows: NumberOfRows,
NumberOfColumns: NumberOfColumns,
NumberOfChans: NumberOfChans,
SubframeDivisions: SubframeDivisions,
FileName: FileName,
DastardVersion: Build.Version,
GitHash: Build.Githash,
ChanName: chanName,
ChannelNumberMatchingName: ChannelNumberMatchingName,
SourceName: sourceName,
ColumnNum: colNum,
RowNum: rowNum,
SubframeOffset: SubframeOffset,
PixelXPosition: pixel.X,
PixelYPosition: pixel.Y,
PixelName: pixel.Name,
}
dp.LJH22 = &w
dp.WritingPaused = false
dp.numberWritten = 0
}
// HasLJH22 returns true if LJH22 is non-nil, used to decide if writeint to LJH22 should occur
func (dp *DataPublisher) HasLJH22() bool {
return dp.LJH22 != nil
}
// RemoveLJH22 closes existing LJH22 file and assign .LJH22=nil
func (dp *DataPublisher) RemoveLJH22() {
if dp.LJH22 != nil {
dp.LJH22.Close()
}
dp.LJH22 = nil
dp.numberWritten = 0
}
// HasPubRecords return true if publishing records on PortTrigs Pub is occuring
func (dp *DataPublisher) HasPubRecords() bool {
return dp.PubRecordsChan != nil
}
// SetPubRecords starts publishing records with zmq4 over tcp at port=PortTrigs
func (dp *DataPublisher) SetPubRecords() {
if PubRecordsChan == nil {
configurePubRecordsSocket()
}
if dp.PubRecordsChan == nil {
dp.PubRecordsChan = PubRecordsChan
}
}
// RemovePubRecords stops publishing records on PortTrigs
func (dp *DataPublisher) RemovePubRecords() {
dp.PubRecordsChan = nil
}
// HasPubSummaries return true if publishing summaries on PortSummaries Pub is occuring
func (dp *DataPublisher) HasPubSummaries() bool {
return dp.PubSummariesChan != nil
}
// SetPubSummaries starts publishing records with zmq4 over tcp at port=PortSummaries
func (dp *DataPublisher) SetPubSummaries() {
if PubSummariesChan == nil {
configurePubSummariesSocket()
}
if dp.PubSummariesChan == nil {
dp.PubSummariesChan = PubSummariesChan
}
}
// RemovePubSummaries stop publing summaries on PortSummaires
func (dp *DataPublisher) RemovePubSummaries() {
dp.PubSummariesChan = nil
}
// PublishData looks at each member of DataPublisher, and if it is non-nil, publishes each record into that member.
// The first step is to publish the full record and/or a record summary to the relevant ZMQ ports.
// The second is to store the records into any active LJH22, LJH3, and/or OFF writers.
func (dp *DataPublisher) PublishData(records []*DataRecord) error {
if len(records) == 0 {
return nil
}
// Publish the records to the ZMQ ports for full records and/or record summaries.
if dp.HasPubRecords() {
dp.PubRecordsChan <- records
}
if dp.HasPubSummaries() {
dp.PubSummariesChan <- records
}
// If writing is paused or there are no active file outputs, then we are done publishing.
if dp.WritingPaused {
return nil
}
if !(dp.HasLJH22() || dp.HasLJH3() || dp.HasOFF()) {
return nil
}
// If we get here, there is one or more output active.
// The LJH and OFF files are _not_ created until they are needed, so each type first checks if the file
// is already opened and has a header written.
if dp.HasLJH22() {
if !dp.LJH22.HeaderWritten {
err := dp.LJH22.CreateFile()
if err != nil {
return err
}
t0 := records[0].trigTime
dp.LJH22.WriteHeader(t0)
}
for _, record := range records {
nano := record.trigTime.UnixNano()
dp.LJH22.WriteRecord(int64(record.trigFrame), int64(nano)/1000, rawTypeToUint16(record.data))
}
}
if dp.HasLJH3() {
if !dp.LJH3.HeaderWritten {
err := dp.LJH3.CreateFile()
if err != nil {
return err
}
dp.LJH3.WriteHeader()
}
for _, record := range records {
nano := record.trigTime.UnixNano()
dp.LJH3.WriteRecord(int32(record.presamples+1), int64(record.trigFrame), int64(nano)/1000, rawTypeToUint16(record.data))
}
}
if dp.HasOFF() {
if !dp.OFF.HeaderWritten() {
err := dp.OFF.CreateFile()
if err != nil {
return err
}
dp.OFF.WriteHeader()
}
for _, record := range records {
modelCoefs := make([]float32, len(record.modelCoefs))
for i, v := range record.modelCoefs {
modelCoefs[i] = float32(v)
}
err := dp.OFF.WriteRecord(int32(len(record.data)), int32(record.presamples), int64(record.trigFrame), record.trigTime.UnixNano(),
float32(record.pretrigMean), float32(record.pretrigDelta), float32(record.residualStdDev), modelCoefs)
if err != nil {
return err
}
}
}
dp.numberWritten += len(records)
return nil
}
// messageSummaries makes a message with the following format for publishing on portTrigs
// Structure of the message header is defined in BINARY_FORMATS.md
// uint16: channel number
// uint16: header version number
// uint32: bits: Presamples
// uint32: length of record
// float32: pretrigMean
// float32: peakValue
// float32: pulseRMS
// float32: pulseAverage
// float32: residualStdDev
// uint64: UnixNano trigTime
// uint64: trigFrame
//
// end of first message packet
// modelCoefs, each coef is float32, length can vary
func messageSummaries(rec *DataRecord) [][]byte {
const headerVersion = uint16(0)
header := new(bytes.Buffer)
header.Write(getbytes.FromUint16(uint16(rec.channelIndex)))
header.Write(getbytes.FromUint16(headerVersion))
header.Write(getbytes.FromUint32(uint32(rec.presamples)))
header.Write(getbytes.FromUint32(uint32(len(rec.data))))
header.Write(getbytes.FromFloat32(float32(rec.pretrigMean)))
header.Write(getbytes.FromFloat32(float32(rec.peakValue)))
header.Write(getbytes.FromFloat32(float32(rec.pulseRMS)))
header.Write(getbytes.FromFloat32(float32(rec.pulseAverage)))
header.Write(getbytes.FromFloat32(float32(rec.residualStdDev)))
nano := rec.trigTime.UnixNano()
header.Write(getbytes.FromInt64(nano))
header.Write(getbytes.FromInt64(int64(rec.trigFrame)))
return [][]byte{header.Bytes(), getbytes.FromSliceFloat64(rec.modelCoefs)}
}
// messageRecords makes a message with the following format for publishing on portTrigs
// Structure of the message header is defined in BINARY_FORMATS.md
// uint16: channel number
// uint8: header version number
// uint8: code for data type (0-1 = 8 bits; 2-3 = 16; 4-5 = 32; 6-7 = 64; odd=uint; even=int)
// uint32: # of pre-trigger samples
// uint32: # of samples, total
// float32: sample period, in seconds (float)
// float32: volts per arb conversion (float)
// uint64: trigger time, in ns since epoch 1970
// uint64: trigger frame #
// end of first message packet
// data, each sample is uint16, length given above
func messageRecords(rec *DataRecord) [][]byte {
const headerVersion = uint8(0)
dataType := uint8(3)
if rec.signed { // DataSegment.signed is set deep within a source, then dsp.signed is set equal to DataSegment.signed in process data, then DataRecord.signed is set equal to dsp.signed upon record generation
dataType = uint8(2)
}
header := new(bytes.Buffer)
header.Write(getbytes.FromUint16(uint16(rec.channelIndex)))
header.Write(getbytes.FromUint8(headerVersion))
header.Write(getbytes.FromUint8(dataType))
header.Write(getbytes.FromUint32(uint32(rec.presamples)))
header.Write(getbytes.FromUint32(uint32(len(rec.data))))
header.Write(getbytes.FromFloat32(rec.sampPeriod))
header.Write(getbytes.FromFloat32(rec.voltsPerArb))
nano := rec.trigTime.UnixNano()
header.Write(getbytes.FromInt64(nano))
header.Write(getbytes.FromUint64(uint64(rec.trigFrame)))
data := rawTypeToBytes(rec.data)
return [][]byte{header.Bytes(), data}
}
// Two library-global variables to allow sharing of zmq publisher sockets:
// PubRecordsChan is used to enable multiple different DataPublishers to publish on the same zmq pub socket
var PubRecordsChan chan []*DataRecord
// PubSummariesChan is used to enable multiple different DataPublishers to publish on the same zmq pub socket
var PubSummariesChan chan []*DataRecord
// configurePubRecordsSocket should be run exactly one time.
// It initializes PubFeederChan and launches a goroutine
// that reads from PubFeederChan and publishes records on a ZMQ PUB socket at port PortTrigs.
// This way even if goroutines in different threads want to publish records, they all use the same
// zmq port. The goroutine can be stopped by closing PubRecordsChan.
func configurePubRecordsSocket() error {
if PubRecordsChan != nil {
return fmt.Errorf("run configurePubRecordsSocket only one time")
}
var err error
PubRecordsChan, err = startSocket(Ports.Trigs, messageRecords)
return err
}
// configurePubSummariesSocket should be run exactly one time; analogue of configurePubRecordsSocket
func configurePubSummariesSocket() error {
if PubSummariesChan != nil {
return fmt.Errorf("run configurePubSummariesSocket only one time")
}
var err error
PubSummariesChan, err = startSocket(Ports.Summaries, messageSummaries)
return err
}
// startSocket sets up a ZMQ publisher socket and starts a goroutine to publish
// messages based on any records that appear on a new channel. Returns the
// channel for other routines to fill. Close that channel to destroy the socket.
func startSocket(port int, converter func(*DataRecord) [][]byte) (chan []*DataRecord, error) {
// Not totally sure how to choose this, but it should probably be
// at least as large as number of channels.
const publishChannelDepth = 500
pubchan := make(chan []*DataRecord, publishChannelDepth)
// Socket to talk to clients
hostname := fmt.Sprintf("tcp://*:%d", port)
pubSocket, err := zmq4.NewSocket(zmq4.PUB)
if err != nil {
return nil, err
}
pubSocket.SetSndhwm(100)
if err = pubSocket.Bind(hostname); err != nil {
return nil, err
}
go func() {
for {
records, ok := <-pubchan
if !ok { // Destroy socket when pubchan is closed and drained
pubSocket.Close()
return
}
for _, record := range records {
message := converter(record)
if _, err := pubSocket.SendMessage(message); err != nil {
ProblemLogger.Println("zmq send error publishing a triggered record:", err)
}
}
}
}()
return pubchan, nil
}