forked from lf-edge/eve
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
1636 lines (1586 loc) · 52.6 KB
/
client.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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2023 Zededa, Inc.
// SPDX-License-Identifier: Apache-2.0
package mmdbus
import (
"context"
"errors"
"fmt"
"math"
"net"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/godbus/dbus/v5"
"github.com/lf-edge/eve/pkg/pillar/base"
"github.com/lf-edge/eve/pkg/pillar/types"
"github.com/lf-edge/eve/pkg/pillar/utils/file"
"github.com/lf-edge/eve/pkg/pillar/utils/generics"
"github.com/sirupsen/logrus"
)
const (
// UnavailSignalMetric : given signal metric is not available.
UnavailSignalMetric = 1<<31 - 1 // 2147483647
// UnavailLocAttribute : given location attribute is not available.
UnavailLocAttribute = -(1 << 15) // -32768
)
const (
notifChanBuffer = 128
dbusSigChanBuffer = 256
dbusCallTimeout = 10 * time.Second
scanProvidersTimeout = 3 * time.Minute
modemDisableTimeout = 10 * time.Second
changePrimarySIMTimeout = 30 * time.Second
changeInitEPSBearerTimeout = 20 * time.Second
)
const (
// SIMStateAbsent : SIM card is not present in the SIM slot.
SIMStateAbsent = "absent"
// SIMStatePresent : SIM card is present in the SIM slot.
SIMStatePresent = "present"
// SIMStateInactive : SIM slot is not activated (SIM card presence is unknown).
SIMStateInactive = "inactive"
// SIMStateError = SIM slot/card is in failed state.
SIMStateError = "error"
)
// Client provides methods for communicating with ModemManager via D-Bus.
type Client struct {
mutex sync.Mutex
log *base.LogObject
conn *dbus.Conn
mmObj dbus.BusObject
lastMsg time.Time
modems map[string]*Modem // key: Modem.Path
// Modem state monitoring
notifChan chan Notification
monitorWG sync.WaitGroup
monitorCtx context.Context
monitorCancel context.CancelFunc
sigPollPeriodSecs uint32
}
// Modem encapsulates all properties of a cellular modem.
type Modem struct {
// Modem object path in DBus.
Path string
// DBus paths of all bearers used by the modem.
BearerPaths []string
// DBus paths of all SIM slots/cards of the modem.
SIMPaths []string
// Note that LogicalLabel is not set or known by Client.
// Similarly, ConfigError and ProbeError are updated by MMAgent,
// Client leaves them empty.
// Client also does not set VisibleProviders, but provides method
// ScanVisibleProviders to get data for this field.
Status types.WwanNetworkStatus
Metrics types.WwanNetworkMetrics
// Location is only available if modem has GNSS receiver and location tracking
// is enabled.
Location types.WwanLocationInfo
}
// ConnectionArgs encapsulates all arguments for connection request.
type ConnectionArgs struct {
types.CellularAccessPoint
DecryptedUsername string
DecryptedPassword string
}
// Event is used to signal change in modem state data.
type Event uint8
const (
// EventUndefined : undefined event (never actually published).
EventUndefined Event = iota
// EventAddedModem : a new cellular modem was detected by ModemManager.
EventAddedModem
// EventRemovedModem : a previously existing cellular modem is no longer present.
EventRemovedModem
// EventUpdatedModemStatus : some properties inside Modem.Status have changed.
EventUpdatedModemStatus
// EventUpdatedModemMetrics : Modem.Metrics have been updated.
EventUpdatedModemMetrics
// EventUpdatedModemLocation : Modem.Location has been updated.
EventUpdatedModemLocation
)
// Notification published to watcher (MMAgent).
type Notification struct {
Event Event
Modem Modem
}
// NewClient is a constructor for Client.
func NewClient(log *base.LogObject) (*Client, error) {
var err error
client := new(Client)
client.log = log
client.conn, err = dbus.SystemBus()
if err != nil {
return nil, err
}
client.mmObj = client.conn.Object(MMInterface, MMObjectPath)
return client, nil
}
// RunModemMonitoring starts Go routine that monitors changes in the state
// of cellular modems as reported by ModemManager, parses and stores obtained
// modem attributes into pillar's Wwan* types and publishes notifications
// summarizing the latest state to the agent.
// Returns initial state data for all modems and a channel through which state changes
// will be announced.
func (c *Client) RunModemMonitoring(signalPollPeriod time.Duration) (
initialState []Modem, notifs <-chan Notification) {
c.mutex.Lock()
defer c.mutex.Unlock()
c.notifChan = make(chan Notification, notifChanBuffer)
c.startModemMonitor()
c.reloadModems()
c.setSignalPollPeriod(signalPollPeriod)
for _, modem := range c.modems {
c.setupSignalPolling(dbus.ObjectPath(modem.Path))
initialState = append(initialState, *modem)
}
return initialState, c.notifChan
}
// Set rate for signal quality periodic polling.
// Zero poll period disables polling.
func (c *Client) setSignalPollPeriod(period time.Duration) {
c.sigPollPeriodSecs = uint32(period.Seconds())
if c.sigPollPeriodSecs == 0 && period > 0 {
// Smallest support period.
c.sigPollPeriodSecs = 1
}
}
func (c *Client) setupSignalPolling(modemPath dbus.ObjectPath) {
modemObj := c.conn.Object(MMInterface, modemPath)
err := c.callDBusMethod(modemObj, SignalMethodSetup, nil, c.sigPollPeriodSecs)
if err != nil {
c.log.Errorf("failed to setup signal polling period %d secs for modem %s: %v",
c.sigPollPeriodSecs, modemPath, err)
}
}
// Starts a new Go routine for modem state monitoring.
// Client should be already locked by the caller.
func (c *Client) startModemMonitor() {
c.monitorCtx, c.monitorCancel = context.WithCancel(context.Background())
c.monitorWG.Add(1)
go func() {
defer c.monitorWG.Done()
rule := fmt.Sprintf("type='signal', path_namespace='%s'", MMObjectPath)
c.conn.BusObject().Call(DBusMethodAddMatch, 0, rule)
sigChan := make(chan *dbus.Signal, dbusSigChanBuffer)
defer close(sigChan)
c.conn.Signal(sigChan)
defer c.conn.RemoveSignal(sigChan)
for {
select {
case <-c.monitorCtx.Done():
return
case signal := <-sigChan:
c.mutex.Lock()
c.lastMsg = time.Now()
c.processDbusSignal(signal)
c.mutex.Unlock()
}
}
}()
}
func (c *Client) processDbusSignal(signal *dbus.Signal) {
switch signal.Name {
// See: https://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-objectmanager
case DBusSignalInterfacesAdded:
if len(signal.Body) < 2 {
c.log.Warnf("Unexpected body length for signal %s (%d)",
DBusSignalInterfacesAdded, len(signal.Body))
return
}
path, ok := signal.Body[0].(dbus.ObjectPath)
if !ok {
c.log.Warnf("Failed to convert path from signal %s (%v)",
DBusSignalInterfacesAdded, signal.Body[0])
return
}
if !strings.HasPrefix(string(path), ModemPathPrefix) {
c.log.Warnf("Skipped signal %s for path %s",
DBusSignalInterfacesAdded, path)
return
}
modem, err := c.getModem(path)
if err != nil {
c.log.Error(err)
return
}
prevModem, exists := c.modems[string(path)]
if !exists {
c.setupSignalPolling(path)
c.modems[string(path)] = modem
c.notifChan <- Notification{
Event: EventAddedModem,
Modem: *modem,
}
} else {
// Not expecting new interfaces added under a modem path
// other than the modem interface itself.
c.log.Warnf("Received signal %s for already known modem: %+v",
DBusSignalInterfacesAdded, signal)
if !prevModem.Status.Equal(modem.Status) {
c.notifChan <- Notification{
Event: EventUpdatedModemStatus,
Modem: *modem,
}
}
if prevModem.Metrics != modem.Metrics {
c.notifChan <- Notification{
Event: EventUpdatedModemMetrics,
Modem: *modem,
}
}
if prevModem.Location != modem.Location {
c.notifChan <- Notification{
Event: EventUpdatedModemLocation,
Modem: *modem,
}
}
c.modems[string(path)] = modem
}
// See: https://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-objectmanager
case DBusSignalInterfacesRemoved:
if len(signal.Body) < 2 {
c.log.Warnf("Unexpected body length for signal %s (%d)",
DBusSignalInterfacesRemoved, len(signal.Body))
return
}
path, ok := signal.Body[0].(dbus.ObjectPath)
if !ok {
c.log.Warnf("Failed to convert path from signal %s (%v)",
DBusSignalInterfacesRemoved, signal.Body[0])
return
}
if !strings.HasPrefix(string(path), ModemPathPrefix) {
c.log.Warnf("Skipped signal %s for path %s",
DBusSignalInterfacesRemoved, path)
return
}
removedIntfs, ok := signal.Body[1].([]string)
if !ok {
c.log.Warnf("Failed to convert list of interfaces removed (%v)",
signal.Body[1])
return
}
if !generics.ContainsItem(removedIntfs, ModemInterface) {
c.log.Warnf("Modem %s has removed interfaces "+
"but not including itself: %v", path, removedIntfs)
return
}
modem, exists := c.modems[string(path)]
if !exists {
c.log.Warnf("Received signal %s for unknown modem %s",
DBusSignalInterfacesRemoved, path)
return
}
c.notifChan <- Notification{
Event: EventRemovedModem,
Modem: *modem,
}
delete(c.modems, string(path))
// See: https://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-properties
case DBusSignalPropertiesChanged:
if len(signal.Body) < 3 {
c.log.Warnf("Unexpected body length for signal %s (%d)",
DBusSignalPropertiesChanged, len(signal.Body))
return
}
interfaceName, ok := signal.Body[0].(string)
if !ok {
c.log.Warnf("Failed to convert interface name from signal %s (%v)",
DBusSignalPropertiesChanged, signal.Body[0])
return
}
properties, ok := signal.Body[1].(map[string]dbus.Variant)
if !ok {
c.log.Warnf("Failed to convert properties from signal %s (%v)",
DBusSignalPropertiesChanged, signal.Body[1])
return
}
// Find out which modem(s) has/have changed and in what scope.
var modemPaths []string
var statusChanged, metricsChanged, locationChanged bool
path := string(signal.Path)
switch interfaceName {
case ModemInterface:
for property := range properties {
switch property {
case ModemPropertySignalQualityName:
// Ignore this, we get signal metrics from SignalInterface.
continue
case ModemPropertyRATsName:
// The set of RATs used changed, now we need to get metrics
// from a different property.
metricsChanged = true
fallthrough
default:
statusChanged = true
}
modemPaths = generics.AppendIfNotDuplicate(modemPaths, path)
}
case Modem3GPPInterface:
statusChanged = true
modemPaths = generics.AppendIfNotDuplicate(modemPaths, path)
case SignalInterface:
metricsChanged = true
modemPaths = generics.AppendIfNotDuplicate(modemPaths, path)
case LocationInterface:
for property := range properties {
switch property {
case LocationPropertyEnabledName, LocationPropertySignalsName:
statusChanged = true
case LocationPropertyName:
locationChanged = true
default:
continue
}
modemPaths = generics.AppendIfNotDuplicate(modemPaths, path)
}
case BearerInterface:
for property := range properties {
switch property {
case BearerPropertyConnectedName:
statusChanged = true
// When disconnected, metrics are cleared.
// When connected, metrics are loaded.
metricsChanged = true
case BearerPropertyStatsName:
metricsChanged = true
default:
statusChanged = true
}
}
for _, modem := range c.modems {
if generics.ContainsItem(modem.BearerPaths, path) {
modemPaths = generics.AppendIfNotDuplicate(
modemPaths, modem.Path)
}
}
case SIMInterface:
statusChanged = true
for _, modem := range c.modems {
if generics.ContainsItem(modem.SIMPaths, path) {
modemPaths = generics.AppendIfNotDuplicate(
modemPaths, modem.Path)
}
}
}
// Reload changed state data and publish notification(s).
for _, modemPath := range modemPaths {
modem := c.modems[modemPath]
if modem == nil {
c.log.Warnf("Received %s for unknown modem %s",
DBusSignalPropertiesChanged, modemPath)
continue
}
modemObj := c.conn.Object(MMInterface, dbus.ObjectPath(modemPath))
if statusChanged {
status, bearers, sims, err := c.getModemStatus(modemObj)
if err != nil {
c.log.Error(err)
continue
}
modem.BearerPaths = bearers
modem.SIMPaths = sims
if !modem.Status.Equal(status) {
modem.Status = status
c.notifChan <- Notification{
Event: EventUpdatedModemStatus,
Modem: *modem,
}
}
}
if metricsChanged {
var metrics types.WwanNetworkMetrics
if len(modem.Status.CurrentRATs) > 0 {
metrics = c.getModemMetrics(modemObj,
modem.Status.CurrentRATs[0])
}
metrics.PhysAddrs = modem.Status.PhysAddrs
if modem.Metrics != metrics {
modem.Metrics = metrics
c.notifChan <- Notification{
Event: EventUpdatedModemMetrics,
Modem: *modem,
}
}
}
if locationChanged {
location := c.getModemLocation(modemObj)
if modem.Location != location {
modem.Location = location
c.notifChan <- Notification{
Event: EventUpdatedModemLocation,
Modem: *modem,
}
}
}
}
}
}
// Reloads Client.modems with the latest state data obtained from the ModemManager.
// Client should be already locked by the caller.
func (c *Client) reloadModems() {
c.modems = make(map[string]*Modem)
err := c.callDBusMethod(c.mmObj, MMMethodScanDevices, nil)
if err != nil {
c.log.Warnf("Failed to trigger new scan for connected modem devices: %v", err)
}
managedObjects := make(map[dbus.ObjectPath]interface{})
err = c.callDBusMethod(c.mmObj, DBusMethodManagedObjects, &managedObjects)
if err != nil {
c.log.Errorf("Failed to list modems: %v", err)
return
}
for path := range managedObjects {
modem, err := c.getModem(path)
if err != nil {
c.log.Error(err)
continue
}
c.modems[string(path)] = modem
}
}
func (c *Client) getModem(path dbus.ObjectPath) (*Modem, error) {
modem := &Modem{Path: string(path)}
modemObj := c.conn.Object(MMInterface, path)
status, bearers, sims, err := c.getModemStatus(modemObj)
if err != nil {
return nil, err
}
modem.Status = status
modem.BearerPaths = bearers
modem.SIMPaths = sims
if len(status.CurrentRATs) > 0 {
modem.Metrics = c.getModemMetrics(modemObj, status.CurrentRATs[0])
}
modem.Metrics.PhysAddrs = status.PhysAddrs
modem.Location = c.getModemLocation(modemObj)
return modem, nil
}
// Get modem status.
// Only fails if it cannot determine modem physical addresses.
func (c *Client) getModemStatus(modemObj dbus.BusObject) (
status types.WwanNetworkStatus, bearerPaths, simPaths []string, err error) {
physAddrs, proto, err := c.getModemPhysAddrs(modemObj)
if err != nil {
err = fmt.Errorf("cannot determine modem %s physical addresses: %w",
modemObj.Path(), err)
return
}
status.PhysAddrs = physAddrs
status.Module.ControlProtocol = proto
// Get cellular module info.
_ = getDBusProperty(c, modemObj, ModemPropertyModel, &status.Module.Model)
_ = getDBusProperty(c, modemObj, ModemPropertyRevision, &status.Module.Revision)
_ = getDBusProperty(c, modemObj, ModemPropertyManufacturer, &status.Module.Manufacturer)
_ = getDBusProperty(c, modemObj, ModemPropertyIMEI, &status.Module.IMEI)
status.Module.Name = status.Module.IMEI
var modemState int32
_ = getDBusProperty(c, modemObj, ModemPropertyState, &modemState)
var failReason uint32
switch modemState {
case ModemStateUnknown:
status.Module.OpMode = types.WwanOpModeUnrecognized
case ModemStateRegistered, ModemStateConnecting:
status.Module.OpMode = types.WwanOpModeOnline
case ModemStateConnected:
status.Module.OpMode = types.WwanOpModeConnected
case ModemStateFailed:
_ = getDBusProperty(c, modemObj, ModemPropertyStateFailReason, &failReason)
fallthrough
default:
status.Module.OpMode = types.WwanOpModeOffline
}
var powerState uint32
_ = getDBusProperty(c, modemObj, ModemPropertyPowerState, &powerState)
if powerState == ModemPowerStateOff || powerState == ModemPowerStateLow {
status.Module.OpMode = types.WwanOpModeRadioOff
}
// Get SIM info.
var primarySIM uint32
_ = getDBusProperty(c, modemObj, ModemPropertyPrimarySIMSlot, &primarySIM)
if primarySIM == 0 {
// Multiple SIM slots not supported on this modem.
primarySIM = 1
}
var simSlots []dbus.ObjectPath
_ = getDBusProperty(c, modemObj, ModemPropertySIMSlots, &simSlots)
if len(simSlots) == 0 {
// Multiple SIM slots not supported on this modem.
var simSlot dbus.ObjectPath
_ = getDBusProperty(c, modemObj, ModemPropertySIM, &simSlot)
if simSlot.IsValid() {
simSlots = append(simSlots, simSlot)
}
}
for i, simPath := range simSlots {
slot := uint8(i + 1)
isPrimary := uint32(slot) == primarySIM
simCard := types.WwanSimCard{
SlotNumber: slot,
SlotActivated: isPrimary,
Type: types.SimTypeUnspecified,
State: SIMStateAbsent,
}
if simPath.IsValid() && len(simPath) > 1 {
simPaths = append(simPaths, string(simPath))
simObj := c.conn.Object(MMInterface, simPath)
_ = getDBusProperty(c, simObj, SIMPropertyActive, &simCard.SlotActivated)
_ = getDBusProperty(c, simObj, SIMPropertyICCID, &simCard.ICCID)
simCard.Name = simCard.ICCID
_ = getDBusProperty(c, simObj, SIMPropertyIMSI, &simCard.IMSI)
var simType uint32
_ = getDBusProperty(c, simObj, SIMPropertyType, &simType)
switch simType {
case SIMTypeUnknown:
// If the SIM type is not recognized, consider SIM card as present
// if ICCID is not empty.
if simCard.ICCID != "" {
simCard.State = SIMStatePresent
}
case SIMTypeESIM:
// eSIM is not supported by EVE (or even by ModemManager) for connection
// establishment, but we still want to at least publish correct status
// information for the eSIM "slot".
simCard.Type = types.SimTypeEmbedded
var esimStatus uint32
_ = getDBusProperty(c, simObj, SIMPropertyESIMStatus, &esimStatus)
if esimStatus == ESIMWithProfiles {
simCard.State = SIMStatePresent
}
case SIMTypePhysical:
// Since we have valid dbus object for the physical SIM slot, it means
// that the SIM card is present.
// But note that even if SIM card is present but the slot is inactive,
// ModemManager might report the card as absent, without providing any SIM
// object path to work with.
// On the other hand, with mbimcli we are able to distinguish between
// missing and inactive SIM card:
// mbimcli -p -d /dev/cdc-wdm0 --ms-query-slot-info-status 0
// [/dev/cdc-wdm0] Slot info status retrieved:
// Slot '0': 'state-off'
// (as opposed to 'state-empty')
// With qmicli we can also get this information:
// qmicli -p -d /dev/cdc-wdm0 --uim-get-slot-status
// [/dev/cdc-wdm0] 2 physical slots found:
// Physical slot 1:
// Card status: present
// Slot status: active
// Logical slot: 1
// ICCID: 894921003198100584
// Protocol: uicc
// Num apps: 0
// Is eUICC: no
// Physical slot 2:
// Card status: present
// Slot status: inactive
// ICCID: 89492029226029738490
// Protocol: uicc
// Num apps: 0
// Is eUICC: no
// TODO: should we call mbimcli/qmicli ?
simCard.Type = types.SimTypePhysical
simCard.State = SIMStatePresent
}
if !simCard.SlotActivated {
simCard.State = SIMStateInactive
}
if isPrimary && modemState == ModemStateFailed {
if failReason == ModemStateFailedReasonSimError {
simCard.State = SIMStateError
}
}
}
status.SimCards = append(status.SimCards, simCard)
}
if len(status.SimCards) == 0 && modemState == ModemStateFailed &&
failReason == ModemStateFailedReasonSimMissing {
status.SimCards = append(status.SimCards,
types.WwanSimCard{
SlotNumber: 1,
SlotActivated: true,
State: SIMStateAbsent,
})
}
// Get RAT info.
var currentRATs uint32
_ = getDBusProperty(c, modemObj, ModemPropertyRATs, ¤tRATs)
if currentRATs&AccessTechnologies5G > 0 {
status.CurrentRATs = append(status.CurrentRATs, types.WwanRAT5GNR)
}
if currentRATs&AccessTechnologies4G > 0 {
status.CurrentRATs = append(status.CurrentRATs, types.WwanRATLTE)
}
if currentRATs&AccessTechnologies3G > 0 {
status.CurrentRATs = append(status.CurrentRATs, types.WwanRATUMTS)
}
if currentRATs&AccessTechnologies2G > 0 {
status.CurrentRATs = append(status.CurrentRATs, types.WwanRATGSM)
}
if currentRATs&^AccessTechnologiesSupported > 0 {
c.log.Errorf("Modem %s is using unsupported RAT: %v",
modemObj.Path(), currentRATs)
}
// Get info about the current provider.
var regState uint32
_ = getDBusProperty(c, modemObj, Modem3GPPPropertyRegistrationState, ®State)
switch regState {
case RegistrationStateDenied:
status.CurrentProvider.Forbidden = true
case RegistrationStateRoaming, RegistrationStateRoamingSmsOnly,
RegistrationStateRoamingCsfbNotPreferred:
status.CurrentProvider.Roaming = true
}
var plmn, providerName string
_ = getDBusProperty(c, modemObj, Modem3GPPPropertyPLMN, &plmn)
_ = getDBusProperty(c, modemObj, Modem3GPPPropertyProviderName, &providerName)
if plmn != "" {
status.CurrentProvider.CurrentServing = true
status.CurrentProvider.PLMN = plmn
status.CurrentProvider.Description = providerName
}
var bearers []dbus.ObjectPath
_ = getDBusProperty(c, modemObj, ModemPropertyBearers, &bearers)
for _, bearerPath := range bearers {
if !bearerPath.IsValid() {
continue
}
bearerPaths = append(bearerPaths, string(bearerPath))
bearerObj := c.conn.Object(MMInterface, bearerPath)
var connected bool
_ = getDBusProperty(c, bearerObj, BearerPropertyConnected, &connected)
if !connected {
continue
}
var stats map[string]dbus.Variant
_ = getDBusProperty(c, bearerObj, BearerPropertyStats, &stats)
if value, ok := stats["start-date"].Value().(uint64); ok {
status.ConnectedAt = value
} else if value, ok := stats["duration"].Value().(uint32); ok {
status.ConnectedAt = uint64(time.Now().Unix()) - uint64(value)
}
ipSettings, err := c.getBearerIPSettings(bearerObj)
if err != nil {
c.log.Error(err)
break
}
status.IPSettings = ipSettings
break
}
// Find out if location tracking is running for this modem.
var locEnabled uint32
_ = getDBusProperty(c, modemObj, LocationPropertyEnabled, &locEnabled)
var locSignals bool
_ = getDBusProperty(c, modemObj, LocationPropertySignals, &locSignals)
status.LocationTracking = locSignals && (locEnabled&LocationSourceGpsRaw) > 0
return
}
func (c *Client) getBearerIPSettings(bearerObj dbus.BusObject) (
ipSettings types.WwanIPSettings, err error) {
var ipConfig map[string]dbus.Variant
var ipLen = net.IPv4len
err = getDBusProperty(c, bearerObj, BearerPropertyIPv4Config, &ipConfig)
if err != nil {
// Try IPv6 config, but if it also fails, then return the error received
// for the IPv4 config.
err2 := getDBusProperty(c, bearerObj, BearerPropertyIPv6Config, &ipConfig)
if err2 != nil {
return
}
ipLen = net.IPv6len
}
if value, ok := ipConfig["method"].Value().(uint32); ok {
if value != BearerIPMethodStatic {
err = fmt.Errorf("connected to bearer %s using unsupported method: %d",
bearerObj.Path(), value)
return
}
}
address, addressOK := ipConfig["address"].Value().(string)
prefix, prefixOK := ipConfig["prefix"].Value().(uint32)
if addressOK && prefixOK {
mask := net.CIDRMask(int(prefix), ipLen*8)
ip := net.ParseIP(address)
if ip == nil {
err = fmt.Errorf("failed to parse modem IP address: %v", address)
return
}
ipSettings.Address = &net.IPNet{IP: ip, Mask: mask}
}
gateway, gatewayOK := ipConfig["gateway"].Value().(string)
if gatewayOK {
ip := net.ParseIP(gateway)
if ip == nil {
err = fmt.Errorf("failed to parse gateway IP address: %v", gateway)
return
}
ipSettings.Gateway = ip
}
for _, dnsServerKey := range []string{"dns1", "dns2", "dns3"} {
if dnsServer, ok := ipConfig[dnsServerKey].Value().(string); ok {
ip := net.ParseIP(dnsServer)
if ip == nil {
err = fmt.Errorf("failed to parse DNS server IP address: %v", dnsServer)
return
}
ipSettings.DNSServers = append(ipSettings.DNSServers, ip)
}
}
if mtu, ok := ipConfig["mtu"].Value().(uint32); ok {
ipSettings.MTU = uint16(mtu)
}
return
}
func (c *Client) getModemPhysAddrs(modemObj dbus.BusObject) (
addrs types.WwanPhysAddrs, proto types.WwanCtrlProt, err error) {
var primaryPort string
// Find device file representing the modem (e.g. /dev/cdc-wdm0).
err = getDBusProperty(c, modemObj, ModemPropertyPrimaryPort, &primaryPort)
if err != nil {
return addrs, proto, err
}
addrs.Dev = filepath.Join("/dev/", primaryPort)
// Find path inside the /sys filesystem pointing to the USB port/interface
// used to control the modem.
devPathSymlink := filepath.Join("/sys/class/usbmisc", primaryPort, "device")
devPath, err := filepath.EvalSymlinks(devPathSymlink)
if err != nil {
// Maybe this modem uses PCIe interface as opposed to USB.
// This is more and more common for modern high-speed 4G and 5G modems.
var err2 error
devPathSymlink2 := filepath.Join("/sys/class/wwan", primaryPort, "device")
devPath, err2 = filepath.EvalSymlinks(devPathSymlink2)
if err2 != nil {
return addrs, proto, fmt.Errorf("failed to eval symlinks %s (%w) and %s (%v)",
devPathSymlink, err, devPathSymlink2, err2)
}
}
// Determine the network interface name.
netPath := filepath.Join(devPath, "net")
netInterfaces, err := os.ReadDir(netPath)
if err != nil {
return addrs, proto, fmt.Errorf("failed to read %s: %w", netPath, err)
}
if len(netInterfaces) > 0 {
addrs.Interface = netInterfaces[0].Name()
}
// Determine USB address.
addrs.USB, err = c.getSysDevAddr(devPath, "usb")
if err != nil {
return addrs, proto, err
}
if addrs.USB != "" {
// Return USB address as <bus>:<port>
// Note that USB paths in /sys/bus/usb/devices have format:
// <bus>-<port>:<config>.<interface>
// We are not interested in the configuration and interface numbers.
addrs.USB = strings.Split(addrs.USB, ":")[0]
addrs.USB = strings.ReplaceAll(addrs.USB, "-", ":")
}
// Determine PCI address.
addrs.PCI, err = c.getSysDevAddr(devPath, "pci")
if err != nil {
return addrs, proto, err
}
// Find out which protocol is being used to control the modem.
var ports [][]interface{}
err = getDBusProperty(c, modemObj, ModemPropertyPorts, &ports)
if err != nil {
return addrs, proto, err
}
for _, port := range ports {
if len(port) != 2 {
continue
}
portName, ok := port[0].(string)
if !ok {
continue
}
portType, ok := port[1].(uint32)
if !ok {
continue
}
if portName == primaryPort {
switch portType {
case ModemPortTypeQMI:
proto = types.WwanCtrlProtQMI
case ModemPortTypeMBIM:
proto = types.WwanCtrlProtMBIM
}
break
}
}
return addrs, proto, nil
}
// Given device path from /sys, such as: /sys/devices/pci0000:00/0000:00:1c.0/0000:2c:00.0/mhi0/wwan/wwan0
// it returns the address of the device on the given bus (e.g. "0000:2c:00.0" for "pci").
// If the device is not on the particular bus, it returns an empty string (and not an error).
func (c *Client) getSysDevAddr(sysDevPath, bus string) (addr string, err error) {
parentPath := sysDevPath
for parentPath != "/" {
// Not every parent directory contains "subsystem" link.
subSysSymlink := filepath.Join(parentPath, "subsystem")
if utils.FileExists(c.log, subSysSymlink) {
subSysPath, err := filepath.EvalSymlinks(subSysSymlink)
if err != nil {
return "", fmt.Errorf("failed to eval symlink %s: %w",
subSysSymlink, err)
}
if filepath.Base(subSysPath) == bus {
return filepath.Base(parentPath), nil
}
}
parentPath = filepath.Dir(parentPath)
}
return "", nil
}
// Get modem metrics.
// Note that WwanNetworkMetrics.PhysAddrs is not filled in by this method.
func (c *Client) getModemMetrics(
modemObj dbus.BusObject, rat types.WwanRAT) types.WwanNetworkMetrics {
metrics := types.WwanNetworkMetrics{
SignalInfo: types.WwanSignalInfo{
RSSI: UnavailSignalMetric,
RSRQ: UnavailSignalMetric,
RSRP: UnavailSignalMetric,
SNR: UnavailSignalMetric,
},
}
// Get signal info
var signal map[string]dbus.Variant
switch rat {
case types.WwanRATGSM:
_ = getDBusProperty(c, modemObj, SignalPropertyGSM, &signal)
case types.WwanRATUMTS:
_ = getDBusProperty(c, modemObj, SignalPropertyUMTS, &signal)
case types.WwanRATLTE:
_ = getDBusProperty(c, modemObj, SignalPropertyLTE, &signal)
case types.WwanRAT5GNR:
_ = getDBusProperty(c, modemObj, SignalProperty5G, &signal)
}
if value, ok := signal["rssi"].Value().(float64); ok {
metrics.SignalInfo.RSSI = int32(value)
}
if value, ok := signal["rsrq"].Value().(float64); ok {
metrics.SignalInfo.RSRQ = int32(value)
}
if value, ok := signal["rsrp"].Value().(float64); ok {
metrics.SignalInfo.RSRP = int32(value)
}
if value, ok := signal["snr"].Value().(float64); ok {
metrics.SignalInfo.SNR = int32(value)
}
// Get traffic stats.
var bearers []dbus.ObjectPath
_ = getDBusProperty(c, modemObj, ModemPropertyBearers, &bearers)
for _, bearerPath := range bearers {
if !bearerPath.IsValid() {
continue
}
bearerObj := c.conn.Object(MMInterface, bearerPath)
var connected bool
_ = getDBusProperty(c, bearerObj, BearerPropertyConnected, &connected)
if !connected {
continue
}
var stats map[string]dbus.Variant
_ = getDBusProperty(c, bearerObj, BearerPropertyStats, &stats)
if value, ok := stats["rx-bytes"].Value().(uint64); ok {
metrics.PacketStats.RxBytes = value
}
if value, ok := stats["tx-bytes"].Value().(uint64); ok {
metrics.PacketStats.TxBytes = value
}
// TODO: Packet and drop counters are not available.
// Use qmicli/mbimcli to get them?
break
}
return metrics
}
func (c *Client) getModemLocation(modemObj dbus.BusObject) types.WwanLocationInfo {
location := types.WwanLocationInfo{
Latitude: UnavailLocAttribute,
Longitude: UnavailLocAttribute,
Altitude: UnavailLocAttribute,
}
var locData map[uint32]dbus.Variant
_ = getDBusProperty(c, modemObj, LocationProperty, &locData)
if data, ok := locData[LocationSourceGpsRaw].Value().(map[string]dbus.Variant); ok {
if value, ok := data["latitude"].Value().(float64); ok {
location.Latitude = value
}
if value, ok := data["longitude"].Value().(float64); ok {
location.Longitude = value
}
if value, ok := data["altitude"].Value().(float64); ok {
location.Altitude = value
}
if value, ok := data["utc-time"].Value().(string); ok {
timeInDay, err := time.Parse(LocationTimestampLayout, value)
if err == nil {
currentDate := time.Now().UTC()
// Combine the date from currentDate with the parsed timeInDay.
completeTime := time.Date(
currentDate.Year(), currentDate.Month(), currentDate.Day(),
timeInDay.Hour(), timeInDay.Minute(), timeInDay.Second(),
timeInDay.Nanosecond(), time.UTC,
)
location.UTCTimestamp = uint64(completeTime.UnixMilli())
} else {
c.log.Errorf("Failed to parse time (%s) provided by GNSS module: %v",
value, err)
}
}
}
return location
}
// PauseModemMonitoring pauses monitoring of modem state changes.
// Call returned function to resume monitoring and to obtain a checkpoint of the current
// modem state data, incl. metrics and location info, from which subsequent notifications
// will follow.
func (c *Client) PauseModemMonitoring() (resume func() (newInitialState []Modem)) {
c.monitorCancel()
c.monitorWG.Wait()
return func() (modems []Modem) {
c.mutex.Lock()
defer c.mutex.Unlock()
c.startModemMonitor()
c.reloadModems()
for _, modem := range c.modems {
c.setupSignalPolling(dbus.ObjectPath(modem.Path))
modems = append(modems, *modem)
}
return modems
}
}
// LastSeenMM returns time when the ModemManager was last seen communicating
// over D-Bus.
func (c *Client) LastSeenMM() time.Time {
c.mutex.Lock()
defer c.mutex.Unlock()
return c.lastMsg
}
// GetMMVersion returns version of the ModemManager.
func (c *Client) GetMMVersion() (string, error) {
c.mutex.Lock()
defer c.mutex.Unlock()