[VOL-3024] - MIB download - provide basic omci configuration to ONU

Change-Id: I6d1547280a27656824136bd3989c4cdcd903c9a2
Signed-off-by: Holger Hildebrandt <holger.hildebrandt@adtran.com>
diff --git a/internal/pkg/onuadaptercore/device_handler.go b/internal/pkg/onuadaptercore/device_handler.go
index e3f74e9..dac5177 100644
--- a/internal/pkg/onuadaptercore/device_handler.go
+++ b/internal/pkg/onuadaptercore/device_handler.go
@@ -802,7 +802,7 @@
 		unigMap, ok := dh.GetOnuDeviceEntry().pOnuDB.meDb[me.UniGClassID]
 		unigInstKeys := dh.GetOnuDeviceEntry().pOnuDB.GetSortedInstKeys(unigMap)
 		if ok {
-			i := uint16(0)
+			i := uint8(0) //UNI Port limit: see MaxUnisPerOnu (by now 16) (OMCI supports max 255 p.b.)
 			for _, mgmtEntityId := range unigInstKeys {
 				logger.Debugw("Add UNI port for stored UniG instance:", log.Fields{"deviceId": dh.GetOnuDeviceEntry().deviceID, "UnigMe EntityID": mgmtEntityId})
 				dh.addUniPort(mgmtEntityId, i, UniPPTP)
@@ -821,28 +821,25 @@
 			if pMibDlFsm.Is("disabled") {
 				if err := pMibDlFsm.Event("start"); err != nil {
 					logger.Errorw("MibDownloadFsm: Can't go to state starting", log.Fields{"err": err})
-					// maybe try a FSM restart and then again ... - TODO!!!
+					// maybe try a FSM reset and then again ... - TODO!!!
 				} else {
 					logger.Debug("MibDownloadFsm", log.Fields{"state": string(pMibDlFsm.Current())})
 					// maybe use more specific states here for the specific download steps ...
-					if err := pMibDlFsm.Event("download_mib"); err != nil {
-						logger.Errorw("MibDownloadFsm: Can't go to state downloading", log.Fields{"err": err})
+					if err := pMibDlFsm.Event("create_gal"); err != nil {
+						logger.Errorw("MibDownloadFsm: Can't start CreateGal", log.Fields{"err": err})
 					} else {
 						logger.Debug("state of MibDownloadFsm", log.Fields{"state": string(pMibDlFsm.Current())})
-						//Begin MIB data download
+						//Begin MIB data download (running autonomously)
 					}
 				}
 			} else {
 				logger.Errorw("wrong state of MibDownloadFsm - want: disabled", log.Fields{"have": string(pMibDlFsm.Current())})
+				// maybe try a FSM reset and then again ... - TODO!!!
 			}
 			/***** Mib download started */
 		} else {
 			logger.Errorw("MibDownloadFsm invalid - cannot be executed!!", log.Fields{"deviceID": dh.deviceID})
 		}
-
-		//shortcut code to fake download-done!!!:  TODO!!! to be removed with complete DL FSM
-		go dh.GetOnuDeviceEntry().transferSystemEvent(MibDownloadDone)
-
 	} else if dev_Event == MibDownloadDone {
 		logger.Debugw("MibDownloadDone event: update dev state to 'Oper.Active'", log.Fields{"deviceID": dh.deviceID})
 		//initiate DevStateUpdate
@@ -865,7 +862,7 @@
 	}
 }
 
-func (dh *DeviceHandler) addUniPort(a_uniInstNo uint16, a_uniId uint16, a_portType UniPortType) {
+func (dh *DeviceHandler) addUniPort(a_uniInstNo uint16, a_uniId uint8, a_portType UniPortType) {
 	// parameters are IntfId, OnuId, uniId
 	uniNo := MkUniPortNum(dh.pOnuIndication.GetIntfId(), dh.pOnuIndication.GetOnuId(),
 		uint32(a_uniId))
diff --git a/internal/pkg/onuadaptercore/messageTypes.go b/internal/pkg/onuadaptercore/messageTypes.go
index 05c5fff..b3e9191 100644
--- a/internal/pkg/onuadaptercore/messageTypes.go
+++ b/internal/pkg/onuadaptercore/messageTypes.go
@@ -44,6 +44,7 @@
 
 const (
 	AnyTriggerForMibSyncUploadMib = 0
+	AbortMessageProcessing        = 1
 )
 
 //TODO: place holder to have a second interface variant - to be replaced by real variant later on
diff --git a/internal/pkg/onuadaptercore/mib_download.go b/internal/pkg/onuadaptercore/mib_download.go
index 1a83136..03c328d 100644
--- a/internal/pkg/onuadaptercore/mib_download.go
+++ b/internal/pkg/onuadaptercore/mib_download.go
@@ -18,13 +18,14 @@
 package adaptercoreonu
 
 import (
+	"context"
+	"errors"
+	"time"
+
 	"github.com/looplab/fsm"
 
-	//"sync"
-	//"time"
-
-	//"github.com/opencord/voltha-lib-go/v3/pkg/kafka"
-
+	"github.com/opencord/omci-lib-go"
+	me "github.com/opencord/omci-lib-go/generated"
 	"github.com/opencord/voltha-lib-go/v3/pkg/log"
 	//ic "github.com/opencord/voltha-protos/v3/go/inter_container"
 	//"github.com/opencord/voltha-protos/v3/go/openflow_13"
@@ -32,24 +33,79 @@
 )
 
 func (onuDeviceEntry *OnuDeviceEntry) enterDLStartingState(e *fsm.Event) {
-	logger.Debugw("MibDownload FSM", log.Fields{"Start downloading OMCI MIB in State": e.FSM.Current(), "device-id": onuDeviceEntry.deviceID})
-
+	logger.Debugw("MibDownload FSM", log.Fields{"Start downloading OMCI MIB in state": e.FSM.Current(), "device-id": onuDeviceEntry.deviceID})
+	// in case the used channel is not yet defined (can be re-used after restarts)
+	if onuDeviceEntry.omciMessageReceived == nil {
+		onuDeviceEntry.omciMessageReceived = make(chan bool)
+		logger.Debug("MibDownload FSM - defining the BridgeInit RxChannel")
+	}
 	// start go routine for processing of MibDownload messages
 	go onuDeviceEntry.ProcessMibDownloadMessages()
+	//possibly include a further MibReset here in order to enforce reset of incomplete set data ...(TODO?)
 }
 
-func (onuDeviceEntry *OnuDeviceEntry) enterDownloadingState(e *fsm.Event) {
-	logger.Debugw("MibDownload FSM", log.Fields{"GAL Ethernet Profile set in State": e.FSM.Current(), "device-id": onuDeviceEntry.deviceID})
-	//onuDeviceEntry.PDevOmciCC.sendGalEthernetProfileSet(context.TODO(), ConstDefaultOmciTimeout, true)
+func (onuDeviceEntry *OnuDeviceEntry) enterCreatingGalState(e *fsm.Event) {
+	logger.Debugw("MibDownload FSM", log.Fields{"Tx create::GAL Ethernet Profile in state": e.FSM.Current(), "device-id": onuDeviceEntry.deviceID})
+	meInstance := onuDeviceEntry.PDevOmciCC.sendCreateGalEthernetProfile(context.TODO(), ConstDefaultOmciTimeout, true)
+	//accept also nil as (error) return value for writing to LastTx
+	//  - this avoids misinterpretation of new received OMCI messages
+	onuDeviceEntry.PDevOmciCC.pLastTxMeInstance = meInstance
+}
+
+func (onuDeviceEntry *OnuDeviceEntry) enterSettingOnu2gState(e *fsm.Event) {
+	logger.Debugw("MibDownload FSM", log.Fields{"Tx Set::ONU2-G in state": e.FSM.Current(), "device-id": onuDeviceEntry.deviceID})
+	meInstance := onuDeviceEntry.PDevOmciCC.sendSetOnu2g(context.TODO(), ConstDefaultOmciTimeout, true)
+	//accept also nil as (error) return value for writing to LastTx
+	//  - this avoids misinterpretation of new received OMCI messages
+	onuDeviceEntry.PDevOmciCC.pLastTxMeInstance = meInstance
+}
+
+func (onuDeviceEntry *OnuDeviceEntry) enterBridgeInitState(e *fsm.Event) {
+	logger.Debugw("MibDownload FSM - starting bridge config loop", log.Fields{
+		"in state": e.FSM.Current(), "device-id": onuDeviceEntry.deviceID})
+	go onuDeviceEntry.performInitialBridgeSetup()
 }
 
 func (onuDeviceEntry *OnuDeviceEntry) enterDownloadedState(e *fsm.Event) {
 	logger.Debugw("MibDownload FSM", log.Fields{"send notification to core in State": e.FSM.Current(), "device-id": onuDeviceEntry.deviceID})
 	onuDeviceEntry.transferSystemEvent(MibDownloadDone)
+	//let's reset the state machine in order to release all resources now
+	pMibDlFsm := onuDeviceEntry.pMibDownloadFsm
+	if pMibDlFsm != nil {
+		// obviously calling some FSM event here directly does not work - so trying to decouple it ...
+		go func(a_pAFsm *AdapterFsm) {
+			if a_pAFsm != nil && a_pAFsm.pFsm != nil {
+				a_pAFsm.pFsm.Event("reset")
+			}
+		}(pMibDlFsm)
+	}
+}
+
+func (onuDeviceEntry *OnuDeviceEntry) enterResettingState(e *fsm.Event) {
+	logger.Debugw("MibDownload FSM resetting", log.Fields{"device-id": onuDeviceEntry.deviceID})
+	pMibDlFsm := onuDeviceEntry.pMibDownloadFsm
+	if pMibDlFsm != nil {
+		// abort running message processing
+		mibSyncMsg := Message{
+			Type: TestMsg,
+			Data: TestMessage{
+				TestMessageVal: AbortMessageProcessing,
+			},
+		}
+		pMibDlFsm.commChan <- mibSyncMsg
+
+		//try to restart the FSM to 'disabled'
+		// see DownloadedState: decouple event transfer
+		go func(a_pAFsm *AdapterFsm) {
+			if a_pAFsm != nil && a_pAFsm.pFsm != nil {
+				a_pAFsm.pFsm.Event("restart")
+			}
+		}(pMibDlFsm)
+	}
 }
 
 func (onuDeviceEntry *OnuDeviceEntry) ProcessMibDownloadMessages( /*ctx context.Context*/ ) {
-	logger.Debugw("MibDownload Msg", log.Fields{"Start routine to process OMCI-messages for device-id": onuDeviceEntry.deviceID})
+	logger.Debugw("Start MibDownload Msg processing", log.Fields{"for device-id": onuDeviceEntry.deviceID})
 loop:
 	for {
 		select {
@@ -58,92 +114,200 @@
 		// 	break loop
 		case message, ok := <-onuDeviceEntry.pMibDownloadFsm.commChan:
 			if !ok {
-				logger.Info("MibDownload Msg", log.Fields{"Message couldn't be read from channel for device-id": onuDeviceEntry.deviceID})
+				logger.Info("MibDownload Rx Msg", log.Fields{"Message couldn't be read from channel for device-id": onuDeviceEntry.deviceID})
+				// but then we have to ensure a restart of the FSM as well - as exceptional procedure
+				onuDeviceEntry.pMibDownloadFsm.pFsm.Event("restart")
 				break loop
 			}
-			logger.Debugw("MibDownload Msg", log.Fields{"Received OMCI message for device-id": onuDeviceEntry.deviceID})
+			logger.Debugw("MibDownload Rx Msg", log.Fields{"Received message for device-id": onuDeviceEntry.deviceID})
 
-			if message.Type != OMCI {
-				logger.Warn("MibDownload Msg", log.Fields{"Unknown message type received for device-id": onuDeviceEntry.deviceID,
-					"message.Type": message.Type})
-			} else {
+			switch message.Type {
+			case TestMsg:
+				msg, _ := message.Data.(TestMessage)
+				if msg.TestMessageVal == AbortMessageProcessing {
+					logger.Infow("MibDownload abort ProcessMsg", log.Fields{"for device-id": onuDeviceEntry.deviceID})
+					break loop
+				}
+				logger.Warnw("MibDownload unknown TestMessage", log.Fields{"device-id": onuDeviceEntry.deviceID, "MessageVal": msg.TestMessageVal})
+			case OMCI:
 				msg, _ := message.Data.(OmciMessage)
 				onuDeviceEntry.handleOmciMibDownloadMessage(msg)
+			default:
+				logger.Warn("MibDownload Rx Msg", log.Fields{"Unknown message type received for device-id": onuDeviceEntry.deviceID,
+					"message.Type": message.Type})
 			}
 		}
 	}
-	logger.Info("MibDownload Msg", log.Fields{"Stop receiving messages for device-id": onuDeviceEntry.deviceID})
-	// TODO: only this action?
-	onuDeviceEntry.pMibDownloadFsm.pFsm.Event("restart")
+	logger.Infow("End MibDownload Msg processing", log.Fields{"for device-id": onuDeviceEntry.deviceID})
 }
 
 func (onuDeviceEntry *OnuDeviceEntry) handleOmciMibDownloadMessage(msg OmciMessage) {
-
 	logger.Debugw("Rx OMCI MibDownload Msg", log.Fields{"device-id": onuDeviceEntry.deviceID,
 		"msgType": msg.OmciMsg.MessageType})
 
-	//further analysis could be done here based on msg.OmciMsg.Payload, e.g. verification of error code ...
-	/*
-		switch msg.OmciMsg.MessageType {
-		case omci.MibResetResponseType:
-			msgLayer := (*msg.OmciPacket).Layer(omci.LayerTypeMibResetResponse)
+	switch msg.OmciMsg.MessageType {
+	case omci.CreateResponseType:
+		{
+			msgLayer := (*msg.OmciPacket).Layer(omci.LayerTypeCreateResponse)
 			if msgLayer == nil {
-				logger.Error("Omci Msg layer could not be detected")
+				logger.Error("Omci Msg layer could not be detected for CreateResponse")
 				return
 			}
-			msgObj, msgOk := msgLayer.(*omci.MibResetResponse)
+			msgObj, msgOk := msgLayer.(*omci.CreateResponse)
 			if !msgOk {
-				logger.Error("Omci Msg layer could not be assigned")
+				logger.Error("Omci Msg layer could not be assigned for CreateResponse")
 				return
 			}
-			logger.Debugw("MibResetResponse Data", log.Fields{"data-fields": msgObj})
+			logger.Debugw("CreateResponse Data", log.Fields{"deviceId": onuDeviceEntry.deviceID, "data-fields": msgObj})
 			if msgObj.Result != me.Success {
-				logger.Errorw("Omci MibResetResponse Error - strange - what to do?", log.Fields{"Error": msgObj.Result})
+				logger.Errorw("Omci CreateResponse Error - later: drive FSM to abort state ?", log.Fields{"Error": msgObj.Result})
+				// possibly force FSM into abort or ignore some errors for some messages? store error for mgmt display?
 				return
 			}
-			onuDeviceEntry.PDevOmciCC.sendMibUpload(context.TODO(), ConstDefaultOmciTimeout, true)
-		case omci.MibUploadResponseType:
-			msgLayer := (*msg.OmciPacket).Layer(omci.LayerTypeMibUploadResponse)
-			if msgLayer == nil {
-				logger.Error("Omci Msg layer could not be detected")
-				return
-			}
-			msgObj, msgOk := msgLayer.(*omci.MibUploadResponse)
-			if !msgOk {
-				logger.Error("Omci Msg layer could not be assigned")
-				return
-			}
-			logger.Debugw("MibUploadResponse Data for:", log.Fields{"deviceId": onuDeviceEntry.deviceID, "data-fields": msgObj})
-			// to be verified / reworked !!!
-			onuDeviceEntry.PDevOmciCC.uploadNoOfCmds = msgObj.NumberOfCommands
-			if onuDeviceEntry.PDevOmciCC.uploadSequNo < onuDeviceEntry.PDevOmciCC.uploadNoOfCmds {
-				onuDeviceEntry.PDevOmciCC.sendMibUploadNext(context.TODO(), ConstDefaultOmciTimeout, true)
-			} else {
-				logger.Error("Invalid number of commands received for:", log.Fields{"deviceId": onuDeviceEntry.deviceID, "uploadNoOfCmds": onuDeviceEntry.PDevOmciCC.uploadNoOfCmds})
-				//TODO right action?
-				onuDeviceEntry.MibSyncFsm.Event("timeout")
-			}
-		case omci.MibUploadNextResponseType:
-			msgLayer := (*msg.OmciPacket).Layer(omci.LayerTypeMibUploadNextResponse)
-			if msgLayer == nil {
-				logger.Error("Omci Msg layer could not be detected")
-				return
-			}
-			msgObj, msgOk := msgLayer.(*omci.MibUploadNextResponse)
-			if !msgOk {
-				logger.Error("Omci Msg layer could not be assigned")
-				return
-			}
-			logger.Debugw("MibUploadNextResponse Data for:", log.Fields{"deviceId": onuDeviceEntry.deviceID, "data-fields": msgObj})
+			// maybe there is a way of pushing the specific create response type generally to the FSM
+			//   and let the FSM verify, if the response was according to current state
+			//   and possibly store the element to DB and progress - maybe some future option ...
+			// but as that is not straightforward to me I insert the type checkes manually here
+			//   and feed the FSM with only 'pre-defined' events ...
+			if msgObj.EntityClass == onuDeviceEntry.PDevOmciCC.pLastTxMeInstance.GetClassID() &&
+				msgObj.EntityInstance == onuDeviceEntry.PDevOmciCC.pLastTxMeInstance.GetEntityID() {
+				//store the created ME into DB //TODO??? obviously the Python code does not store the config ...
+				// if, then something like:
+				//onuDeviceEntry.pOnuDB.StoreMe(msgObj)
 
-			onuDeviceEntry.pOnuDB.StoreMe(msgObj)
-
-			if onuDeviceEntry.PDevOmciCC.uploadSequNo < onuDeviceEntry.PDevOmciCC.uploadNoOfCmds {
-				onuDeviceEntry.PDevOmciCC.sendMibUploadNext(context.TODO(), ConstDefaultOmciTimeout, true)
-			} else {
-				//TODO
-				onuDeviceEntry.MibSyncFsm.Event("success")
+				// maybe we can use just the same eventName for different state transitions like "forward"
+				//   - might be checked, but so far I go for sure and have to inspect the concrete state events ...
+				switch onuDeviceEntry.PDevOmciCC.pLastTxMeInstance.GetName() {
+				case "GalEthernetProfile":
+					{ // let the FSM proceed ...
+						onuDeviceEntry.pMibDownloadFsm.pFsm.Event("rx_gal_resp")
+					}
+				case "MacBridgeServiceProfile",
+					"MacBridgePortConfigurationData",
+					"ExtendedVlanTaggingOperationConfigurationData":
+					{ // let bridge init proceed by stopping the wait function
+						onuDeviceEntry.omciMessageReceived <- true
+					}
+				}
 			}
+		} //CreateResponseType
+	//TODO
+	//	onuDeviceEntry.pMibDownloadFsm.pFsm.Event("rx_evtocd_resp")
+
+	case omci.SetResponseType:
+		{
+			msgLayer := (*msg.OmciPacket).Layer(omci.LayerTypeSetResponse)
+			if msgLayer == nil {
+				logger.Error("Omci Msg layer could not be detected for SetResponse")
+				return
+			}
+			msgObj, msgOk := msgLayer.(*omci.SetResponse)
+			if !msgOk {
+				logger.Error("Omci Msg layer could not be assigned for SetResponse")
+				return
+			}
+			logger.Debugw("SetResponse Data for:", log.Fields{"deviceId": onuDeviceEntry.deviceID, "data-fields": msgObj})
+			if msgObj.Result != me.Success {
+				logger.Errorw("Omci SetResponse Error - later: drive FSM to abort state ?", log.Fields{"Error": msgObj.Result})
+				// possibly force FSM into abort or ignore some errors for some messages? store error for mgmt display?
+				return
+			}
+			logger.Debugw("SetResponse Data", log.Fields{"deviceId": onuDeviceEntry.deviceID, "data-fields": msgObj})
+			if msgObj.Result != me.Success {
+				logger.Errorw("Omci SetResponse Error - later: drive FSM to abort state ?", log.Fields{"Error": msgObj.Result})
+				// possibly force FSM into abort or ignore some errors for some messages? store error for mgmt display?
+				return
+			}
+			// compare comments above for CreateResponse (apply also here ...)
+			if msgObj.EntityClass == onuDeviceEntry.PDevOmciCC.pLastTxMeInstance.GetClassID() &&
+				msgObj.EntityInstance == onuDeviceEntry.PDevOmciCC.pLastTxMeInstance.GetEntityID() {
+				//store the created ME into DB //TODO??? obviously the Python code does not store the config ...
+				// if, then something like:
+				//onuDeviceEntry.pOnuDB.StoreMe(msgObj)
+
+				switch onuDeviceEntry.PDevOmciCC.pLastTxMeInstance.GetName() {
+				case "Onu2G":
+					{ // let the FSM proceed ...
+						onuDeviceEntry.pMibDownloadFsm.pFsm.Event("rx_onu2g_resp")
+					}
+					//so far that was the only MibDownlad Set Element ...
+				}
+			}
+
+			// TODO!!!: further needed processing here ....
+
+		} //SetResponseType
+	default:
+		{
+			logger.Errorw("Rx OMCI MibDownload unhandled MsgType", log.Fields{"omciMsgType": msg.OmciMsg.MessageType})
+			return
 		}
-	*/
+	} // switch msg.OmciMsg.MessageType
+}
+
+func (onuDeviceEntry *OnuDeviceEntry) performInitialBridgeSetup() {
+	for uniNo, uniPort := range onuDeviceEntry.baseDeviceHandler.uniEntityMap {
+		logger.Infow("Starting IntialBridgeSetup", log.Fields{
+			"deviceId": onuDeviceEntry.deviceID, "for PortNo": uniNo})
+
+		//create MBSP
+		meInstance := onuDeviceEntry.PDevOmciCC.sendCreateMBServiceProfile(
+			context.TODO(), uniPort, ConstDefaultOmciTimeout, true)
+		onuDeviceEntry.PDevOmciCC.pLastTxMeInstance = meInstance
+		//verify response
+		err := onuDeviceEntry.WaitforOmciResponse(meInstance)
+		if err != nil {
+			logger.Error("InitialBridgeSetup failed at MBSP, aborting MIB Download!")
+			onuDeviceEntry.pMibDownloadFsm.pFsm.Event("reset")
+			return
+		}
+
+		//create MBPCD
+		meInstance = onuDeviceEntry.PDevOmciCC.sendCreateMBPConfigData(
+			context.TODO(), uniPort, ConstDefaultOmciTimeout, true)
+		onuDeviceEntry.PDevOmciCC.pLastTxMeInstance = meInstance
+		//verify response
+		err = onuDeviceEntry.WaitforOmciResponse(meInstance)
+		if err != nil {
+			logger.Error("InitialBridgeSetup failed at MBPCD, aborting MIB Download!")
+			onuDeviceEntry.pMibDownloadFsm.pFsm.Event("reset")
+			return
+		}
+
+		//create EVTOCD
+		meInstance = onuDeviceEntry.PDevOmciCC.sendCreateEVTOConfigData(
+			context.TODO(), uniPort, ConstDefaultOmciTimeout, true)
+		onuDeviceEntry.PDevOmciCC.pLastTxMeInstance = meInstance
+		//verify response
+		err = onuDeviceEntry.WaitforOmciResponse(meInstance)
+		if err != nil {
+			logger.Error("InitialBridgeSetup failed at EVTOCD, aborting MIB Download!")
+			onuDeviceEntry.pMibDownloadFsm.pFsm.Event("reset")
+			return
+		}
+	}
+	// if Config has been done for all UNI related instances let the FSM proceed
+	// while we did not check here, if there is some port at all - !?
+	logger.Infow("IntialBridgeSetup finished", log.Fields{"deviceId": onuDeviceEntry.deviceID})
+	onuDeviceEntry.pMibDownloadFsm.pFsm.Event("rx_bridge_resp")
+	return
+}
+
+func (onuDeviceEntry *OnuDeviceEntry) WaitforOmciResponse(a_pMeInstance *me.ManagedEntity) error {
+	select {
+	// maybe be also some outside cancel (but no context modelled for the moment ...)
+	// case <-ctx.Done():
+	// 		logger.Info("MibDownload-bridge-init message reception canceled", log.Fields{"for device-id": onuDeviceEntry.deviceID})
+	case <-time.After(3 * time.Second):
+		logger.Warnw("MibDownload-bridge-init timeout", log.Fields{"for device-id": onuDeviceEntry.deviceID})
+		return errors.New("MibDownloadBridgeInit timeout")
+	case success := <-onuDeviceEntry.omciMessageReceived:
+		if success == true {
+			logger.Debug("MibDownload-bridge-init response received")
+			return nil
+		}
+		// should not happen so far
+		logger.Warnw("MibDownload-bridge-init response error", log.Fields{"for device-id": onuDeviceEntry.deviceID})
+		return errors.New("MibDownloadBridgeInit responseError")
+	}
 }
diff --git a/internal/pkg/onuadaptercore/omci_cc.go b/internal/pkg/onuadaptercore/omci_cc.go
index c712b1d..972670f 100644
--- a/internal/pkg/onuadaptercore/omci_cc.go
+++ b/internal/pkg/onuadaptercore/omci_cc.go
@@ -23,6 +23,7 @@
 	"encoding/binary"
 	"encoding/hex"
 	"errors"
+	"strconv"
 	"sync"
 
 	//"time"
@@ -42,8 +43,20 @@
 	//"github.com/opencord/voltha-protos/v3/go/voltha"
 )
 
+// ### OMCI related definitions - retrieved from Python adapter code/trace ####
 const ConstDefaultOmciTimeout = 10 // ( 3 ?) Seconds
 
+const galEthernetEID = uint16(1)
+const maxGemPayloadSize = uint16(48)
+const connectivityModeValue = uint8(5)
+const defaultTPID = uint16(0x8100)
+const broadComDefaultVID = uint16(4091)
+const macBridgeServiceProfileEID = uint16(0x201) // TODO: most all these need better definition or tuning
+const ieeeMapperServiceProfileEID = uint16(0x8001)
+const macBridgePortAniEID = uint16(0x2102)
+
+// ### OMCI related definitions - end
+
 //CallbackPair to be used for ReceiveCallback init
 type CallbackPair struct {
 	cbKey      uint16
@@ -80,10 +93,11 @@
 	uploadSequNo   uint16
 	uploadNoOfCmds uint16
 
-	mutexTxQueue    sync.Mutex
-	txQueue         *list.List
-	mutexRxSchedMap sync.Mutex
-	rxSchedulerMap  map[uint16]func(*omci.OMCI, *gp.Packet) error
+	mutexTxQueue      sync.Mutex
+	txQueue           *list.List
+	mutexRxSchedMap   sync.Mutex
+	rxSchedulerMap    map[uint16]func(*omci.OMCI, *gp.Packet) error
+	pLastTxMeInstance *me.ManagedEntity
 }
 
 //NewOmciCC constructor returns a new instance of a OmciCC
@@ -490,12 +504,17 @@
 		TransactionID: tid,
 		MessageType:   msgType,
 	}
+	return serializeOmciLayer(omciLayer, request)
+}
+
+func serializeOmciLayer(a_omciLayer *omci.OMCI, a_request gopacket.SerializableLayer) ([]byte, error) {
 	var options gopacket.SerializeOptions
 	options.FixLengths = true
 
 	buffer := gopacket.NewSerializeBuffer()
-	err := gopacket.SerializeLayers(buffer, options, omciLayer, request)
+	err := gopacket.SerializeLayers(buffer, options, a_omciLayer, a_request)
 	if err != nil {
+		logger.Errorw("Could not create goPacket Omci serial buffer", log.Fields{"Err": err})
 		return nil, err
 	}
 	return buffer.Bytes(), nil
@@ -507,9 +526,6 @@
 	return dst, nil
 }
 
-// ###################################################################################
-// # MIB Action shortcuts  - still dummies - TODO!!!!!
-
 //supply a response handler for the MibSync omci response messages
 func (oo *OmciCC) receiveMibSyncResponse(omciMsg *omci.OMCI, packet *gp.Packet) error {
 
@@ -536,6 +552,31 @@
 	return nil
 }
 
+//supply a response handler for the MibDownload omci response messages
+func (oo *OmciCC) ReceiveMibDownloadResponse(omciMsg *omci.OMCI, packet *gp.Packet) error {
+
+	logger.Debugw("mib-download-omci-message-response received:", log.Fields{"omciMsgType": omciMsg.MessageType,
+		"transCorrId": omciMsg.TransactionID, "deviceId": oo.deviceID})
+
+	if oo.pOnuDeviceEntry == nil {
+		logger.Error("Abort Receive MibDownload OMCI response, DeviceEntryPointer is nil")
+		return errors.New("DeviceEntryPointer is nil")
+	}
+
+	// no further test on SeqNo is done here, assignment from rxScheduler is trusted
+	// MibDownload responses are simply transferred via deviceEntry to MibDownload, no specific analysis here
+	mibDlMsg := Message{
+		Type: OMCI,
+		Data: OmciMessage{
+			OmciMsg:    omciMsg,
+			OmciPacket: packet,
+		},
+	}
+	(*oo.pOnuDeviceEntry).pMibDownloadFsm.commChan <- mibDlMsg
+
+	return nil
+}
+
 func (oo *OmciCC) sendMibReset(ctx context.Context, timeout int, highPrio bool) error {
 
 	logger.Debugw("send MibReset-msg to:", log.Fields{"deviceId": oo.deviceID})
@@ -555,7 +596,6 @@
 }
 
 func (oo *OmciCC) sendMibUpload(ctx context.Context, timeout int, highPrio bool) error {
-
 	logger.Debugw("send MibUpload-msg to:", log.Fields{"deviceId": oo.deviceID})
 	request := &omci.MibUploadRequest{
 		MeBasePacket: omci.MeBasePacket{
@@ -576,7 +616,6 @@
 }
 
 func (oo *OmciCC) sendMibUploadNext(ctx context.Context, timeout int, highPrio bool) error {
-
 	logger.Debugw("send MibUploadNext-msg to:", log.Fields{"deviceId": oo.deviceID, "uploadSequNo": oo.uploadSequNo})
 	request := &omci.MibUploadNextRequest{
 		MeBasePacket: omci.MeBasePacket{
@@ -596,14 +635,232 @@
 	return oo.Send(ctx, pkt, timeout, 0, highPrio, omciRxCallbackPair)
 }
 
-/* py code example
-...
-def send_mib_upload(self, timeout=DEFAULT_OMCI_TIMEOUT, high_priority=False):
-	frame = OntDataFrame().mib_upload()
-	return self.send(frame, timeout=timeout, high_priority=high_priority)
+func (oo *OmciCC) sendCreateGalEthernetProfile(ctx context.Context, timeout int, highPrio bool) *me.ManagedEntity {
+	tid := oo.GetNextTid(highPrio)
+	logger.Debugw("send GalEnetProfile-Create-msg:", log.Fields{"deviceId": oo.deviceID, "SequNo": strconv.FormatInt(int64(tid), 16)})
 
-def send_mib_upload_next(self, seq_no, timeout=DEFAULT_OMCI_TIMEOUT, high_priority=False):
-	frame = OntDataFrame(sequence_number=seq_no).mib_upload_next()
-	return self.send(frame, timeout=timeout, high_priority=high_priority)
-...
-*/
+	meParams := me.ParamData{
+		EntityID:   galEthernetEID,
+		Attributes: me.AttributeValueMap{"MaximumGemPayloadSize": maxGemPayloadSize},
+	}
+	meInstance, omciErr := me.NewGalEthernetProfile(meParams)
+	if omciErr.GetError() == nil {
+		//all setByCreate parameters already set, no default option required ...
+		omciLayer, msgLayer, err := omci.EncodeFrame(meInstance, omci.CreateRequestType, omci.TransactionID(tid))
+		if err != nil {
+			logger.Errorw("Cannot encode GalEnetProfileInstance for create", log.Fields{"Err": err})
+			return nil
+		}
+
+		pkt, err := serializeOmciLayer(omciLayer, msgLayer)
+		if err != nil {
+			logger.Errorw("Cannot serialize GalEnetProfile create", log.Fields{"Err": err})
+			return nil
+		}
+
+		omciRxCallbackPair := CallbackPair{tid, oo.ReceiveMibDownloadResponse}
+		err = oo.Send(ctx, pkt, timeout, 0, highPrio, omciRxCallbackPair)
+		if err != nil {
+			logger.Errorw("Cannot send GalEnetProfile create", log.Fields{"Err": err})
+			return nil
+		} else {
+			logger.Debug("send GalEnetProfile-Create-msg done")
+			return meInstance
+		}
+	} else {
+		logger.Errorw("Cannot generate GalEnetProfileInstance", log.Fields{"Err": omciErr.GetError()})
+		return nil
+	}
+}
+
+// might be needed to extend for parameter arguments, here just for setting the VonnectivityMode!!
+func (oo *OmciCC) sendSetOnu2g(ctx context.Context, timeout int, highPrio bool) *me.ManagedEntity {
+	tid := oo.GetNextTid(highPrio)
+	logger.Debugw("send ONU2-G-Set-msg:", log.Fields{"deviceId": oo.deviceID, "SequNo": strconv.FormatInt(int64(tid), 16)})
+
+	// here we should better use the MibUpload stored ONU2-G data to re-use the given InstanceNumber
+	//   and to verify, if the ONU really supports the desired connectivity mode 5 (in ConnCap)
+	// By now we just use fix values to fire - this is anyway what the python adapter does
+	// read ONU-2G from DB ???? //TODO!!!
+	meParams := me.ParamData{
+		EntityID:   0,
+		Attributes: me.AttributeValueMap{"CurrentConnectivityMode": connectivityModeValue},
+	}
+	meInstance, omciErr := me.NewOnu2G(meParams)
+	if omciErr.GetError() == nil {
+		omciLayer, msgLayer, err := omci.EncodeFrame(meInstance, omci.SetRequestType, omci.TransactionID(tid))
+		if err != nil {
+			logger.Errorw("Cannot encode ONU2-G instance for set", log.Fields{"Err": err})
+			return nil
+		}
+
+		pkt, err := serializeOmciLayer(omciLayer, msgLayer)
+		if err != nil {
+			logger.Errorw("Cannot serialize ONU2-G set", log.Fields{"Err": err})
+			return nil
+		}
+
+		omciRxCallbackPair := CallbackPair{tid, oo.ReceiveMibDownloadResponse}
+		err = oo.Send(ctx, pkt, timeout, 0, highPrio, omciRxCallbackPair)
+		if err != nil {
+			logger.Errorw("Cannot send ONU2-G set", log.Fields{"Err": err})
+			return nil
+		} else {
+			logger.Debug("send ONU2-G-Set-msg done")
+			return meInstance
+		}
+	} else {
+		logger.Errorw("Cannot generate ONU2-G", log.Fields{"Err": omciErr.GetError()})
+		return nil
+	}
+}
+
+func (oo *OmciCC) sendCreateMBServiceProfile(ctx context.Context,
+	a_pUniPort *OnuUniPort, timeout int, highPrio bool) *me.ManagedEntity {
+	tid := oo.GetNextTid(highPrio)
+	instID := macBridgeServiceProfileEID + uint16(a_pUniPort.macBpNo)
+	logger.Debugw("send MBSP-Create-msg:", log.Fields{
+		"deviceId": oo.deviceID, "SequNo": strconv.FormatInt(int64(tid), 16), "InstId": instID})
+
+	meParams := me.ParamData{
+		EntityID: instID,
+		Attributes: me.AttributeValueMap{
+			"Priority":     0x8000,
+			"MaxAge":       20 * 256, //20s
+			"HelloTime":    2 * 256,  //2s
+			"ForwardDelay": 15 * 256, //15s
+			//note: DynamicFilteringAgeingTime is taken from omci lib default as
+			//  which is obviously different from default value used in python lib,
+			//  where the value seems to be 0 (ONU defined)  - to be considered in case of test artifacts ...
+		},
+	}
+
+	meInstance, omciErr := me.NewMacBridgeServiceProfile(meParams)
+	if omciErr.GetError() == nil {
+		//obviously we have to set all 'untouched' parameters to default by some additional option parameter!!
+		omciLayer, msgLayer, err := omci.EncodeFrame(meInstance, omci.CreateRequestType,
+			omci.TransactionID(tid), omci.AddDefaults(true))
+		if err != nil {
+			logger.Errorw("Cannot encode MBSP for create", log.Fields{"Err": err})
+			return nil
+		}
+
+		pkt, err := serializeOmciLayer(omciLayer, msgLayer)
+		if err != nil {
+			logger.Errorw("Cannot serialize MBSP create", log.Fields{"Err": err})
+			return nil
+		}
+
+		omciRxCallbackPair := CallbackPair{tid, oo.ReceiveMibDownloadResponse}
+		err = oo.Send(ctx, pkt, timeout, 0, highPrio, omciRxCallbackPair)
+		if err != nil {
+			logger.Errorw("Cannot send MBSP create", log.Fields{"Err": err})
+			return nil
+		} else {
+			logger.Debug("send MBSP-Create-msg done")
+			return meInstance
+		}
+	} else {
+		logger.Errorw("Cannot generate MBSP Instance", log.Fields{"Err": omciErr.GetError()})
+		return nil
+	}
+}
+
+func (oo *OmciCC) sendCreateMBPConfigData(ctx context.Context,
+	a_pUniPort *OnuUniPort, timeout int, highPrio bool) *me.ManagedEntity {
+	tid := oo.GetNextTid(highPrio)
+	instID := macBridgePortAniEID + a_pUniPort.entityId
+	logger.Debugw("send MBPCD-Create-msg:", log.Fields{
+		"deviceId": oo.deviceID, "SequNo": strconv.FormatInt(int64(tid), 16), "InstId": instID})
+
+	meParams := me.ParamData{
+		EntityID: instID,
+		Attributes: me.AttributeValueMap{
+			"BridgeIdPointer": macBridgeServiceProfileEID + uint16(a_pUniPort.macBpNo),
+			"PortNum":         a_pUniPort.macBpNo,
+			"TpType":          uint8(a_pUniPort.portType),
+			"TpPointer":       a_pUniPort.entityId,
+		},
+	}
+	meInstance, omciErr := me.NewMacBridgePortConfigurationData(meParams)
+	if omciErr.GetError() == nil {
+		//obviously we have to set all 'untouched' parameters to default by some additional option parameter!!
+		omciLayer, msgLayer, err := omci.EncodeFrame(meInstance, omci.CreateRequestType,
+			omci.TransactionID(tid), omci.AddDefaults(true))
+		if err != nil {
+			logger.Errorw("Cannot encode MBPCD for create", log.Fields{"Err": err})
+			return nil
+		}
+
+		pkt, err := serializeOmciLayer(omciLayer, msgLayer)
+		if err != nil {
+			logger.Errorw("Cannot serialize MBPCD create", log.Fields{"Err": err})
+			return nil
+		}
+
+		omciRxCallbackPair := CallbackPair{tid, oo.ReceiveMibDownloadResponse}
+		err = oo.Send(ctx, pkt, timeout, 0, highPrio, omciRxCallbackPair)
+		if err != nil {
+			logger.Errorw("Cannot send MBPCD create", log.Fields{"Err": err})
+			return nil
+		} else {
+			logger.Debug("send MBPCD-Create-msg done")
+			return meInstance
+		}
+	} else {
+		logger.Errorw("Cannot generate MBPCD Instance", log.Fields{"Err": omciErr.GetError()})
+		return nil
+	}
+}
+
+func (oo *OmciCC) sendCreateEVTOConfigData(ctx context.Context,
+	a_pUniPort *OnuUniPort, timeout int, highPrio bool) *me.ManagedEntity {
+	tid := oo.GetNextTid(highPrio)
+	//same entityId is used as for MBSP (see there), but just arbitrary ...
+	instID := macBridgeServiceProfileEID + uint16(a_pUniPort.macBpNo)
+	logger.Debugw("send EVTOCD-Create-msg:", log.Fields{
+		"deviceId": oo.deviceID, "SequNo": strconv.FormatInt(int64(tid), 16), "InstId": instID})
+
+	// compare python adapter code WA VOL-1311: this is not done here!
+	//   (setting TPID values for the create would probably anyway be ignored by the omci lib)
+	//    but perhaps we have to be aware of possible problems at get(Next) Request handling for EVTOOCD tables later ...
+	assType := uint8(2) // default AssociationType is PPTPEthUni
+	if a_pUniPort.portType == UniVEIP {
+		assType = uint8(10) // for VEIP
+	}
+	meParams := me.ParamData{
+		EntityID: instID,
+		Attributes: me.AttributeValueMap{
+			"AssociationType":     assType,
+			"AssociatedMePointer": a_pUniPort.entityId,
+		},
+	}
+	meInstance, omciErr := me.NewExtendedVlanTaggingOperationConfigurationData(meParams)
+	if omciErr.GetError() == nil {
+		//all setByCreate parameters already set, no default option required ...
+		omciLayer, msgLayer, err := omci.EncodeFrame(meInstance, omci.CreateRequestType, omci.TransactionID(tid))
+		if err != nil {
+			logger.Errorw("Cannot encode EVTOCD for create", log.Fields{"Err": err})
+			return nil
+		}
+
+		pkt, err := serializeOmciLayer(omciLayer, msgLayer)
+		if err != nil {
+			logger.Errorw("Cannot serialize EVTOCD create", log.Fields{"Err": err})
+			return nil
+		}
+
+		omciRxCallbackPair := CallbackPair{tid, oo.ReceiveMibDownloadResponse}
+		err = oo.Send(ctx, pkt, timeout, 0, highPrio, omciRxCallbackPair)
+		if err != nil {
+			logger.Errorw("Cannot send EVTOCD create", log.Fields{"Err": err})
+			return nil
+		} else {
+			logger.Debug("send EVTOCD-Create-msg done")
+			return meInstance
+		}
+	} else {
+		logger.Errorw("Cannot generate EVTOCD Instance", log.Fields{"Err": omciErr.GetError()})
+		return nil
+	}
+}
diff --git a/internal/pkg/onuadaptercore/onu_device_entry.go b/internal/pkg/onuadaptercore/onu_device_entry.go
index 62b86c0..2d7caa6 100644
--- a/internal/pkg/onuadaptercore/onu_device_entry.go
+++ b/internal/pkg/onuadaptercore/onu_device_entry.go
@@ -100,6 +100,7 @@
 	pMibDownloadFsm *AdapterFsm //could be handled dynamically and more general as pAdapterFsm - perhaps later
 	//remark: general usage of pAdapterFsm would require generalization of commChan  usage and internal event setting
 	//  within the FSM event procedures
+	omciMessageReceived chan bool //seperate channel needed by DownloadFsm
 }
 
 //OnuDeviceEntry returns a new instance of a OnuDeviceEntry
@@ -186,7 +187,7 @@
 		},
 
 		fsm.Callbacks{
-			"enter_state":                func(e *fsm.Event) { onuDeviceEntry.pMibDownloadFsm.logFsmStateChange(e) },
+			"enter_state":                func(e *fsm.Event) { onuDeviceEntry.pMibUploadFsm.logFsmStateChange(e) },
 			"enter_starting":             func(e *fsm.Event) { onuDeviceEntry.enterStartingState(e) },
 			"enter_loading_mib_template": func(e *fsm.Event) { onuDeviceEntry.enterLoadingMibTemplateState(e) },
 			"enter_uploading":            func(e *fsm.Event) { onuDeviceEntry.enterUploadingState(e) },
@@ -206,20 +207,32 @@
 
 			{Name: "start", Src: []string{"disabled"}, Dst: "starting"},
 
-			{Name: "download_mib", Src: []string{"starting"}, Dst: "downloading"},
+			{Name: "create_gal", Src: []string{"starting"}, Dst: "creatingGal"},
+			{Name: "rx_gal_resp", Src: []string{"creatingGal"}, Dst: "settingOnu2g"},
+			{Name: "rx_onu2g_resp", Src: []string{"settingOnu2g"}, Dst: "bridgeInit"},
+			// the bridge state is used for multi ME config for alle UNI related ports
+			// maybe such could be reflected in the state machine as well (port number parametrized)
+			// but that looks not straightforward here - so we keep it simple here for the beginning(?)
+			{Name: "rx_bridge_resp", Src: []string{"bridgeInit"}, Dst: "downloaded"},
 
-			{Name: "success", Src: []string{"downloading"}, Dst: "downloaded"},
+			{Name: "timeout_simple", Src: []string{"creatingGal", "settingOnu2g"}, Dst: "starting"},
+			{Name: "timeout_bridge", Src: []string{"bridgeInit"}, Dst: "starting"},
 
-			{Name: "timeout", Src: []string{"downloading"}, Dst: "starting"},
-
-			{Name: "restart", Src: []string{"starting", "downloading", "downloaded"}, Dst: "disabled"},
+			{Name: "reset", Src: []string{"starting", "creatingGal", "settingOnu2g",
+				"bridgeInit", "downloaded"}, Dst: "resetting"},
+			// exceptional treatment for all states except "resetting"
+			{Name: "restart", Src: []string{"starting", "creatingGal", "settingOnu2g",
+				"bridgeInit", "downloaded", "resetting"}, Dst: "disabled"},
 		},
 
 		fsm.Callbacks{
-			"enter_state":       func(e *fsm.Event) { onuDeviceEntry.pMibDownloadFsm.logFsmStateChange(e) },
-			"enter_starting":    func(e *fsm.Event) { onuDeviceEntry.enterDLStartingState(e) },
-			"enter_downloading": func(e *fsm.Event) { onuDeviceEntry.enterDownloadingState(e) },
-			"enter_downloaded":  func(e *fsm.Event) { onuDeviceEntry.enterDownloadedState(e) },
+			"enter_state":        func(e *fsm.Event) { onuDeviceEntry.pMibDownloadFsm.logFsmStateChange(e) },
+			"enter_starting":     func(e *fsm.Event) { onuDeviceEntry.enterDLStartingState(e) },
+			"enter_creatingGal":  func(e *fsm.Event) { onuDeviceEntry.enterCreatingGalState(e) },
+			"enter_settingOnu2g": func(e *fsm.Event) { onuDeviceEntry.enterSettingOnu2gState(e) },
+			"enter_bridgeInit":   func(e *fsm.Event) { onuDeviceEntry.enterBridgeInitState(e) },
+			"enter_downloaded":   func(e *fsm.Event) { onuDeviceEntry.enterDownloadedState(e) },
+			"enter_resetting":    func(e *fsm.Event) { onuDeviceEntry.enterResettingState(e) },
 		},
 	)
 	if onuDeviceEntry.pMibDownloadFsm == nil || onuDeviceEntry.pMibDownloadFsm.pFsm == nil {
diff --git a/internal/pkg/onuadaptercore/onu_uni_port.go b/internal/pkg/onuadaptercore/onu_uni_port.go
index f5fc224..a888207 100644
--- a/internal/pkg/onuadaptercore/onu_uni_port.go
+++ b/internal/pkg/onuadaptercore/onu_uni_port.go
@@ -36,21 +36,23 @@
 
 type UniPortType uint8
 
+// UniPPTP Interface type - re-use values from G.988 TP type definition (directly used in OMCI!)
 const (
-	// Uni Interface type
-	UniPPTP UniPortType = 0 // relates to PPTP
-	UniVEIP UniPortType = 1 // relates to VEIP
+	// UniPPTP relates to PPTP
+	UniPPTP UniPortType = 1 // relates to PPTP
+	// UniPPTP relates to VEIP
+	UniVEIP UniPortType = 11 // relates to VEIP
 )
 
-//OntDeviceEntry structure holds information about the attached FSM'as and their communication
+//OnuUniPort structure holds information about the ONU attached Uni Ports
 type OnuUniPort struct {
 	enabled    bool
 	name       string
 	portNo     uint32
 	portType   UniPortType
 	ofpPortNo  string
-	uniId      uint16
-	macBpNo    uint16
+	uniId      uint8
+	macBpNo    uint8
 	entityId   uint16
 	adminState vc.AdminState_Types
 	operState  vc.OperStatus_Types
@@ -58,7 +60,7 @@
 }
 
 //NewOnuUniPort returns a new instance of a OnuUniPort
-func NewOnuUniPort(a_uniId uint16, a_portNo uint32, a_InstNo uint16,
+func NewOnuUniPort(a_uniId uint8, a_portNo uint32, a_InstNo uint16,
 	a_portType UniPortType) *OnuUniPort {
 	logger.Infow("init-onuUniPort", log.Fields{"uniId": a_uniId,
 		"portNo": a_portNo, "InstNo": a_InstNo, "type": a_portType})