|
| 1 | +// This file is part of arduino-cli. |
| 2 | +// |
| 3 | +// Copyright 2021 ARDUINO SA (http://www.arduino.cc/) |
| 4 | +// |
| 5 | +// This software is released under the GNU General Public License version 3, |
| 6 | +// which covers the main part of arduino-cli. |
| 7 | +// The terms of this license can be found at: |
| 8 | +// https://www.gnu.org/licenses/gpl-3.0.en.html |
| 9 | +// |
| 10 | +// You can be released from the requirements of the above licenses by purchasing |
| 11 | +// a commercial license. Buying such a license is mandatory if you want to |
| 12 | +// modify or otherwise use the software for commercial activities involving the |
| 13 | +// Arduino software without disclosing the source code of your own applications. |
| 14 | +// To purchase a commercial license, send an email to [email protected]. |
| 15 | + |
| 16 | +package monitors |
| 17 | + |
| 18 | +import ( |
| 19 | + "log" |
| 20 | + "time" |
| 21 | +) |
| 22 | + |
| 23 | +// NullMonitor outputs zeros at a constant rate and discards anything sent |
| 24 | +type NullMonitor struct { |
| 25 | + started time.Time |
| 26 | + sent int |
| 27 | + bps float64 |
| 28 | +} |
| 29 | + |
| 30 | +// OpenNullMonitor creates a monitor that outputs the same character at a fixed |
| 31 | +// rate. |
| 32 | +func OpenNullMonitor(bytesPerSecondRate float64) *NullMonitor { |
| 33 | + log.Printf("Started streaming at %f\n", bytesPerSecondRate) |
| 34 | + return &NullMonitor{ |
| 35 | + started: time.Now(), |
| 36 | + bps: bytesPerSecondRate, |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +// Close the connection |
| 41 | +func (mon *NullMonitor) Close() error { |
| 42 | + return nil |
| 43 | +} |
| 44 | + |
| 45 | +// Read bytes from the port |
| 46 | +func (mon *NullMonitor) Read(bytes []byte) (int, error) { |
| 47 | + for { |
| 48 | + elapsed := time.Now().Sub(mon.started).Seconds() |
| 49 | + n := int(elapsed*mon.bps) - mon.sent |
| 50 | + if n == 0 { |
| 51 | + // Delay until the next char... |
| 52 | + time.Sleep(time.Millisecond) |
| 53 | + continue |
| 54 | + } |
| 55 | + if len(bytes) < n { |
| 56 | + n = len(bytes) |
| 57 | + } |
| 58 | + mon.sent += n |
| 59 | + for i := 0; i < n; i++ { |
| 60 | + bytes[i] = 0 |
| 61 | + } |
| 62 | + return n, nil |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +// Write bytes to the port |
| 67 | +func (mon *NullMonitor) Write(bytes []byte) (int, error) { |
| 68 | + // Discard all chars |
| 69 | + return len(bytes), nil |
| 70 | +} |
0 commit comments