[VOL-4420] Add support for POTS UNI ports to bbsim

Change-Id: Ibb817ced6086c3ef3001f338d98513101ce64c1c
diff --git a/internal/bbsim/devices/olt.go b/internal/bbsim/devices/olt.go
index cf658eb..8520bf2 100644
--- a/internal/bbsim/devices/olt.go
+++ b/internal/bbsim/devices/olt.go
@@ -20,12 +20,13 @@
 	"context"
 	"encoding/hex"
 	"fmt"
-	"github.com/opencord/voltha-protos/v5/go/extension"
 	"net"
 	"strconv"
 	"sync"
 	"time"
 
+	"github.com/opencord/voltha-protos/v5/go/extension"
+
 	"github.com/opencord/bbsim/internal/bbsim/responders/dhcp"
 	"github.com/opencord/bbsim/internal/bbsim/types"
 	omcilib "github.com/opencord/bbsim/internal/common/omci"
@@ -79,6 +80,7 @@
 	NumPon               int
 	NumOnuPerPon         int
 	NumUni               int
+	NumPots              int
 	InternalState        *fsm.FSM
 	channel              chan types.Message
 	dhcpServer           dhcp.DHCPServerIf
@@ -124,6 +126,7 @@
 		"NumPon":       options.Olt.PonPorts,
 		"NumOnuPerPon": options.Olt.OnusPonPort,
 		"NumUni":       options.Olt.UniPorts,
+		"NumPots":      options.Olt.PotsPorts,
 	}).Debug("CreateOLT")
 
 	olt = OltDevice{
@@ -136,6 +139,7 @@
 		NumPon:              int(options.Olt.PonPorts),
 		NumOnuPerPon:        int(options.Olt.OnusPonPort),
 		NumUni:              int(options.Olt.UniPorts),
+		NumPots:             int(options.Olt.PotsPorts),
 		Pons:                []*PonPort{},
 		Nnis:                []*NniPort{},
 		Delay:               options.BBSim.Delay,
diff --git a/internal/bbsim/devices/onu.go b/internal/bbsim/devices/onu.go
index 97c1adc..cfc7099 100644
--- a/internal/bbsim/devices/onu.go
+++ b/internal/bbsim/devices/onu.go
@@ -108,9 +108,10 @@
 
 	Backoff *backoff.Backoff
 	// ONU State
-	UniPorts []UniPortIf
-	Flows    []FlowKey
-	FlowIds  []uint64 // keep track of the flows we currently have in the ONU
+	UniPorts  []UniPortIf
+	PotsPorts []PotsPortIf
+	Flows     []FlowKey
+	FlowIds   []uint64 // keep track of the flows we currently have in the ONU
 
 	OperState    *fsm.FSM
 	SerialNumber *openolt.SerialNumber
@@ -290,6 +291,11 @@
 					_ = uni.Disable()
 				}
 
+				// disable the POTS UNI ports
+				for _, pots := range o.PotsPorts {
+					_ = pots.Disable()
+				}
+
 				// verify all the flows removes are handled and
 				// terminate the ONU's ProcessOnuMessages Go routine
 				// NOTE may need to wait for the UNIs to be down too before shutting down the channel
@@ -316,11 +322,14 @@
 		},
 	)
 	onuLogger.WithFields(log.Fields{
-		"OnuId":  o.ID,
-		"IntfId": o.PonPortID,
-		"OnuSn":  o.Sn(),
-		"NumUni": olt.NumUni,
+		"OnuId":   o.ID,
+		"IntfId":  o.PonPortID,
+		"OnuSn":   o.Sn(),
+		"NumUni":  olt.NumUni,
+		"NumPots": olt.NumPots,
 	}).Debug("creating-uni-ports")
+
+	// create Ethernet UNIs
 	for i := 0; i < olt.NumUni; i++ {
 		uni, err := NewUniPort(uint32(i), &o, nextCtag, nextStag)
 		if err != nil {
@@ -333,8 +342,21 @@
 		}
 		o.UniPorts = append(o.UniPorts, uni)
 	}
+	// create POTS UNIs, with progressive IDs
+	for i := olt.NumUni; i < (olt.NumUni + olt.NumPots); i++ {
+		pots, err := NewPotsPort(uint32(i), &o)
+		if err != nil {
+			onuLogger.WithFields(log.Fields{
+				"OnuId":  o.ID,
+				"IntfId": o.PonPortID,
+				"OnuSn":  o.Sn(),
+				"Err":    err,
+			}).Fatal("cannot-create-pots-port")
+		}
+		o.PotsPorts = append(o.PotsPorts, pots)
+	}
 
-	mibDb, err := omcilib.GenerateMibDatabase(len(o.UniPorts))
+	mibDb, err := omcilib.GenerateMibDatabase(len(o.UniPorts), len(o.PotsPorts))
 	if err != nil {
 		onuLogger.WithFields(log.Fields{
 			"OnuId":  o.ID,
@@ -827,6 +849,33 @@
 					}).Warn("cannot-change-uni-status")
 				}
 			}
+		case me.PhysicalPathTerminationPointPotsUniClassID:
+			// if we're Setting a PPTP state
+			// we need to send the appropriate alarm (handled in the POTS struct)
+			pots, err := o.FindPotsByEntityId(msgObj.EntityInstance)
+			if err != nil {
+				onuLogger.Error(err)
+				success = false
+			} else {
+				// 1 locks the UNI, 0 unlocks it
+				adminState := msgObj.Attributes["AdministrativeState"].(uint8)
+				var err error
+				if adminState == 1 {
+					err = pots.Disable()
+				} else {
+					err = pots.Enable()
+				}
+				if err != nil {
+					onuLogger.WithFields(log.Fields{
+						"IntfId":       o.PonPortID,
+						"OnuId":        o.ID,
+						"PotsMeId":     pots.MeId,
+						"PotsId":       pots.ID,
+						"SerialNumber": o.Sn(),
+						"Err":          err.Error(),
+					}).Warn("cannot-change-pots-status")
+				}
+			}
 		case me.OnuGClassID:
 			o.AdminLockState = msgObj.Attributes["AdministrativeState"].(uint8)
 			onuLogger.WithFields(log.Fields{
@@ -1239,6 +1288,17 @@
 	return nil, fmt.Errorf("cannot-find-uni-with-id-%d-on-onu-%s", uniID, o.Sn())
 }
 
+// FindPotsById retrieves a POTS port by ID
+func (o *Onu) FindPotsById(uniID uint32) (*PotsPort, error) {
+	for _, p := range o.PotsPorts {
+		pots := p.(*PotsPort)
+		if pots.ID == uniID {
+			return pots, nil
+		}
+	}
+	return nil, fmt.Errorf("cannot-find-pots-with-id-%d-on-onu-%s", uniID, o.Sn())
+}
+
 // FindUniByEntityId retrieves a uni by MeID (the OMCI entity ID)
 func (o *Onu) FindUniByEntityId(meId uint16) (*UniPort, error) {
 	entityId := omcilib.EntityID{}.FromUint16(meId)
@@ -1251,6 +1311,18 @@
 	return nil, fmt.Errorf("cannot-find-uni-with-meid-%s-on-onu-%s", entityId.ToString(), o.Sn())
 }
 
+// FindPotsByEntityId retrieves a POTS uni by MeID (the OMCI entity ID)
+func (o *Onu) FindPotsByEntityId(meId uint16) (*PotsPort, error) {
+	entityId := omcilib.EntityID{}.FromUint16(meId)
+	for _, p := range o.PotsPorts {
+		pots := p.(*PotsPort)
+		if pots.MeId.Equals(entityId) {
+			return pots, nil
+		}
+	}
+	return nil, fmt.Errorf("cannot-find-pots-with-meid-%s-on-onu-%s", entityId.ToString(), o.Sn())
+}
+
 func (o *Onu) SetID(id uint32) {
 	onuLogger.WithFields(log.Fields{
 		"IntfId":       o.PonPortID,
diff --git a/internal/bbsim/devices/onu_test.go b/internal/bbsim/devices/onu_test.go
index bb5f0c1..35f0c28 100644
--- a/internal/bbsim/devices/onu_test.go
+++ b/internal/bbsim/devices/onu_test.go
@@ -17,8 +17,9 @@
 package devices
 
 import (
-	"github.com/stretchr/testify/assert"
 	"testing"
+
+	"github.com/stretchr/testify/assert"
 )
 
 func Test_Onu_CreateOnu(t *testing.T) {
@@ -26,8 +27,9 @@
 	nextStag := map[string]int{}
 
 	olt := OltDevice{
-		ID:     0,
-		NumUni: 4,
+		ID:      0,
+		NumUni:  4,
+		NumPots: 1,
 	}
 	pon := PonPort{
 		ID:  1,
@@ -38,4 +40,5 @@
 
 	assert.Equal(t, "BBSM00000101", onu.Sn())
 	assert.Equal(t, 4, len(onu.UniPorts))
+	assert.Equal(t, 1, len(onu.PotsPorts))
 }
diff --git a/internal/bbsim/devices/pots_port.go b/internal/bbsim/devices/pots_port.go
new file mode 100644
index 0000000..820f723
--- /dev/null
+++ b/internal/bbsim/devices/pots_port.go
@@ -0,0 +1,124 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+
+ * http://www.apache.org/licenses/LICENSE-2.0
+
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package devices
+
+import (
+	"fmt"
+
+	"github.com/looplab/fsm"
+	bbsimTypes "github.com/opencord/bbsim/internal/bbsim/types"
+	omcilib "github.com/opencord/bbsim/internal/common/omci"
+	log "github.com/sirupsen/logrus"
+)
+
+var potsLogger = log.WithFields(log.Fields{
+	"module": "POTS",
+})
+
+const (
+	PotsStateUp   = "up"
+	PotsStateDown = "down"
+
+	potsTxEnable  = "enable"
+	potsTxDisable = "disable"
+)
+
+type PotsPortIf interface {
+	Enable() error
+	Disable() error
+}
+
+type PotsPort struct {
+	ID        uint32
+	MeId      omcilib.EntityID
+	PortNo    uint32
+	OperState *fsm.FSM
+	Onu       *Onu
+	logger    *log.Entry
+}
+
+func NewPotsPort(ID uint32, onu *Onu) (*PotsPort, error) {
+	pots := PotsPort{
+		ID:   ID,
+		Onu:  onu,
+		MeId: omcilib.GenerateUniPortEntityId(ID + 1),
+	}
+
+	pots.logger = potsLogger.WithFields(log.Fields{
+		"PotsUniId": pots.ID,
+		"OnuSn":     onu.Sn(),
+	})
+
+	pots.OperState = fsm.NewFSM(
+		PotsStateDown,
+		fsm.Events{
+			{Name: potsTxEnable, Src: []string{PotsStateDown}, Dst: PotsStateUp},
+			{Name: potsTxDisable, Src: []string{PotsStateUp}, Dst: PotsStateDown},
+		},
+		fsm.Callbacks{
+			"enter_state": func(e *fsm.Event) {
+				pots.logger.Debugf("changing-pots-operstate-from-%s-to-%s", e.Src, e.Dst)
+			},
+			fmt.Sprintf("enter_%s", PotsStateUp): func(e *fsm.Event) {
+				msg := bbsimTypes.Message{
+					Type: bbsimTypes.UniStatusAlarm,
+					Data: bbsimTypes.UniStatusAlarmMessage{
+						OnuSN:          pots.Onu.SerialNumber,
+						OnuID:          pots.Onu.ID,
+						AdminState:     0,
+						EntityID:       pots.MeId.ToUint16(),
+						RaiseOMCIAlarm: false, // never raise an LOS when enabling a UNI
+					},
+				}
+				pots.Onu.Channel <- msg
+			},
+			fmt.Sprintf("enter_%s", PotsStateDown): func(e *fsm.Event) {
+				msg := bbsimTypes.Message{
+					Type: bbsimTypes.UniStatusAlarm,
+					Data: bbsimTypes.UniStatusAlarmMessage{
+						OnuSN:          pots.Onu.SerialNumber,
+						OnuID:          pots.Onu.ID,
+						AdminState:     1,
+						EntityID:       pots.MeId.ToUint16(),
+						RaiseOMCIAlarm: true, // raise an LOS when disabling a UNI
+					},
+				}
+				pots.Onu.Channel <- msg
+			},
+		},
+	)
+
+	return &pots, nil
+}
+
+func (u *PotsPort) StorePortNo(portNo uint32) {
+	u.PortNo = portNo
+	u.logger.WithFields(log.Fields{
+		"PortNo": portNo,
+	}).Debug("logical-port-number-added-to-pots")
+}
+
+func (u *PotsPort) Enable() error {
+	return u.OperState.Event(potsTxEnable)
+}
+
+func (u *PotsPort) Disable() error {
+	if u.OperState.Is(PotsStateDown) {
+		return nil
+	}
+	return u.OperState.Event(potsTxDisable)
+}
diff --git a/internal/bbsim/devices/pots_port_test.go b/internal/bbsim/devices/pots_port_test.go
new file mode 100644
index 0000000..6a23b76
--- /dev/null
+++ b/internal/bbsim/devices/pots_port_test.go
@@ -0,0 +1,73 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+
+ * http://www.apache.org/licenses/LICENSE-2.0
+
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package devices
+
+import (
+	"testing"
+
+	bbsimTypes "github.com/opencord/bbsim/internal/bbsim/types"
+	"github.com/stretchr/testify/assert"
+)
+
+func createTestPots() (*PotsPort, error) {
+	onu := &Onu{
+		ID:           0,
+		SerialNumber: NewSN(1, 1, 1),
+		PonPortID:    0,
+		Channel:      make(chan bbsimTypes.Message),
+	}
+
+	pots, err := NewPotsPort(1, onu)
+
+	return pots, err
+}
+
+func Test_Pots_Create(t *testing.T) {
+	pots, err := createTestPots()
+
+	assert.Nil(t, err)
+	assert.NotNil(t, pots)
+
+	// check initial operational state
+	assert.Equal(t, pots.OperState.Current(), PotsStateDown)
+}
+
+func Test_Pots_OperationalState(t *testing.T) {
+	pots, _ := createTestPots()
+
+	assert.Equal(t, pots.OperState.Current(), PotsStateDown)
+
+	go func() {
+		//When it will be enabled
+		msg, ok := <-pots.Onu.Channel
+		assert.True(t, ok)
+		assert.Equal(t, uint8(0), msg.Data.(bbsimTypes.UniStatusAlarmMessage).AdminState)
+
+		//When it will be disabled
+		msg, ok = <-pots.Onu.Channel
+		assert.True(t, ok)
+		assert.Equal(t, uint8(1), msg.Data.(bbsimTypes.UniStatusAlarmMessage).AdminState)
+	}()
+
+	err := pots.Enable()
+	assert.Nil(t, err)
+	assert.Equal(t, PotsStateUp, pots.OperState.Current())
+
+	err = pots.Disable()
+	assert.Nil(t, err)
+	assert.Equal(t, PotsStateDown, pots.OperState.Current())
+}