How to use initFromConfigFile method of run Package

Best Venom code snippet using run.initFromConfigFile

m3.go

Source:m3.go Github

copy

Full Screen

1//*********************************************************************************/2// Copyright 2017 www.igismo.com. All rights reserved. See open source license3// HISTORY:4// NAME REV DATE REMARKS @5// Goran Scuric 1.0 01012018 Initial design goran@usa.net by igismo6// Goran Scuric 2.0 09012019 Adapted for bifrost project7// Goran Scuric 3.0 12012020 Adapted for AeroMesh Space Mesh Networking8//=================================================================================9// COMMAND LINE OPTIONS:10// FORMAT: sudo ./drone [DroneName DroneId [myIP [myPort [groundIP [groundPort]]]]]11// use 0 anywhere for default12// EXAMPLE1: sudo ./aeroMeshNode DroneX 01 192.168.22.2 1201 192.168.1.1 120013//=================================================================================14// SYNAPSE VERSION 2021/2215//================================================================================16package main17import (18 "fmt"19 "github.com/igismo/synapse/commonTB"20 "github.com/spf13/viper"21 "net"22 "os"23 "os/exec"24 //"reflect"25 "runtime"26 "strconv"27 "strings"28 "time"29)30//const DEBUG_ROLE = 031//const DEBUG_DISCOVERY = 032var M3 common.M3Info // all info about the Node33var Log = common.LogInstance{} // for log file storage34const StateDown = "DOWN"35const StateConnecting = "CONNECTING"36const StateConnected = "CONNECTED"37// REMOTE_CMD Command from local terminal, or rcvd from ground controller38// const LOCAL_CMD = "LOCAL"39const REMOTE_CMD = "REMOTE"40// InitM3Configuration InitDroneConfiguration ======================================41// READ ARGUMENTS IF ANY42//====================================================================================43func InitM3Configuration() {44 M3.M3TerminalName = "Node01" // will be overwritten by config45 M3.M3TerminalId = 1 // will be overwritten by config46 M3.M3TerminalIP = ""47 M3.TerminalConnectionTimer = common.DRONE_KEEPALIVE_TIMER // 5 sec48 M3.TerminalDiscoveryTimeout = 5000 // milli sec49 M3.Channels.CmdChannel = nil // so that all local threads can talk back50 M3.Channels.UnicastRcvCtrlChannel = nil // to send control msgs to Recv Thread51 M3.Channels.BroadcastRcvCtrlChannel = nil52 M3.Channels.MulticastRcvCtrlChannel = nil53 // M3.TerminalConnection = nil54 M3.TerminalReceiveCount = 055 M3.TerminalSendCount = 056 Log.DebugLog = true57 Log.WarningLog = true58 Log.ErrorLog = true59 M3.Channels.UnicastRcvCtrlChannel = make(chan []byte) //60 M3.Channels.BroadcastRcvCtrlChannel = make(chan []byte)61 M3.Channels.MulticastRcvCtrlChannel = make(chan []byte)62 M3.Channels.CmdChannel = make(chan []string) // receive command line cmnds63 M3.Connectivity.BroadcastRxAddress = ":48999"64 M3.Connectivity.BroadcastRxPort = "48999"65 M3.Connectivity.BroadcastRxIP = ""66 M3.Connectivity.BroadcastTxPort = "48888"67 M3.Connectivity.BroadcastConnection = nil68 M3.Connectivity.BroadcastTxStruct = new(net.UDPAddr)69 M3.Connectivity.UnicastRxAddress = ":48888"70 M3.Connectivity.UnicastRxPort = "48888"71 M3.Connectivity.UnicastRxIP = ""72 M3.Connectivity.UnicastTxPort = "48888"73 M3.Connectivity.UnicastConnection = nil74 M3.Connectivity.UnicastRxStruct = nil75 M3.Connectivity.UnicastTxStruct = new(net.UDPAddr)76 M3.GroundIsKnown = false77 M3.GroundUdpPort = 078 M3.GroundIP = ""79 M3.M3TerminalPort = "8888"80 M3.GroundIPandPort = "" //M3.GroundIP + ":" + M3.GroundUdpPort81 M3.TerminalUdpAddrStructure = new(net.UDPAddr)82 M3.GroundUdpAddrSTR = new(net.UDPAddr)83 M3.TerminalTimeCreated = time.Now() // strconv.FormatInt(common.TBtimestampNano(), 10)84}85// InitFromConfigFile ================================================================86// InitFromConfigFile() - Set configuration from config file87//====================================================================================88func InitFromConfigFile() {89 var fileName string90 argNum := len(os.Args) // Number of arguments supplied, including the command91 fmt.Println("Number of Arguments = ", argNum)92 if argNum > 2 && os.Args[1] != "" && os.Args[1] != "0" {93 M3.M3TerminalName = os.Args[1]94 M3.M3TerminalId, _ = strconv.Atoi(os.Args[2])95 fileName = "config" + os.Args[2] + ".yml"96 viper.SetConfigName(fileName)97 } else {98 // Set the file name of the configurations file99 fileName = "config.yml"100 viper.SetConfigName(fileName)101 }102 // Set the path to look for the configurations file103 viper.AddConfigPath(".")104 // Enable VIPER to read Environment Variables105 viper.AutomaticEnv()106 viper.SetConfigType("yml")107 // var droneStruct DroneInfo108 if err := viper.ReadInConfig(); err != nil {109 fmt.Printf("Error reading config file, %s", err)110 return111 }112 // Set undefined variables113 viper.SetDefault("DroneName", "Drone1")114 // store configuration into the drone structure115 err := viper.Unmarshal(&M3) //&droneStruct)116 if err != nil {117 fmt.Printf("Unable to decode into struct, %v", err)118 }119 fmt.Println("Reading variables from ... config", fileName)120 fmt.Println("*************************************************************")121 fmt.Println("TerminalId = ", M3.M3TerminalId)122 fmt.Println("TerminalName = ", M3.M3TerminalName)123 fmt.Println("TerminalIP = ", M3.M3TerminalIP)124 fmt.Println("TerminalLogPath = ", M3.TerminalLogPath)125 fmt.Println("TerminalConnectionTimer = ", M3.TerminalConnectionTimer)126 fmt.Println("TerminalPort = ", M3.M3TerminalPort)127 fmt.Println("BroadcastRxIP = ", M3.Connectivity.BroadcastRxIP)128 fmt.Println("BroadcastRxPort = ", M3.Connectivity.BroadcastRxPort)129 M3.Connectivity.BroadcastRxAddress =130 M3.Connectivity.BroadcastRxIP + ":" + M3.Connectivity.BroadcastRxPort131 fmt.Println("BroadcastRxAddress = ", M3.Connectivity.BroadcastRxAddress)132 fmt.Println("UnicastRxIP = ", M3.Connectivity.UnicastRxIP)133 fmt.Println("UnicastRxPort = ", M3.Connectivity.UnicastRxPort)134 M3.Connectivity.UnicastRxAddress =135 M3.Connectivity.UnicastRxIP + ":" + M3.Connectivity.UnicastRxPort136 fmt.Println("UnicastRxAddress = ", M3.Connectivity.UnicastRxAddress)137 fmt.Println("BroadcastTxIP = ", M3.Connectivity.BroadcastTxIP)138 fmt.Println("BroadcastTxPort = ", M3.Connectivity.BroadcastTxPort)139 M3.Connectivity.BroadcastTxAddress =140 M3.Connectivity.BroadcastTxIP + ":" + M3.Connectivity.BroadcastTxPort141 fmt.Println("BroadcastTxAddress = ", M3.Connectivity.BroadcastTxAddress)142 fmt.Println("GroundId = ", M3.GroundIP)143 fmt.Println("GroundUdpPort = ", M3.GroundUdpPort)144 fmt.Println("GroundIPandPort = ", M3.GroundIPandPort)145}146// InitFromCommandLine ====================================================================================147// InitFromCommandLine() READ ARGUMENTS IF ANY148//====================================================================================149func InitFromCommandLine() {150 // argsWithProg := os.Args; argsWithoutProg := os.Args[1:]151 // Second: check for the command line parametersz, they overwrite the config file152 for index := range os.Args {153 arg := os.Args[index]154 fmt.Println("Arg", index, "=", arg)155 }156 argNum := len(os.Args) // Number of arguments supplied, including the command157 fmt.Println("Number of Arguments = ", argNum)158 if argNum > 2 && os.Args[1] != "" && os.Args[1] != "0" {159 fmt.Println("M3 NAME = ", os.Args[1])160 M3.M3TerminalName = os.Args[1]161 M3.M3TerminalId, _ = strconv.Atoi(os.Args[2])162 }163 if argNum > 3 && os.Args[3] != "" && os.Args[3] != "0" {164 fmt.Println("Satellite IP = ", os.Args[3])165 M3.M3TerminalIP = os.Args[3]166 // TODO: Set eth0 IP address to M3.M3IpAddress !!!167 var ifCmd = exec.Command("sudo", "ifconfig", "eth0",168 M3.M3TerminalIP, "up", "", "")169 output, err := ifCmd.Output()170 fmt.Println("SET MY IP=", "sudo", "ifconfig", "eth0", M3.M3TerminalIP, "up",171 " -OUTPUT:", string(output), " ERR:", err)172 }173 if argNum > 4 && os.Args[4] != "" && os.Args[4] != "0" {174 M3.M3TerminalPort = os.Args[4] // strconv.ParseInt(os.Args[3], 10, 64)175 }176 if argNum > 5 && os.Args[5] != "" && os.Args[5] != "0" && argNum > 6 && os.Args[6] != "" && os.Args[6] != "0" {177 M3.GroundIPandPort = os.Args[5] + ":" + os.Args[6]178 }179}180// SetFinalM3Info ===============================================================181// Initialize my own info in the M3 structure182//===============================================================================183func SetFinalM3Info() {184 if M3.M3TerminalIP == "" {185 M3.M3TerminalIP, M3.M3TerminalMac = common.GetLocalIp() // get IP and MAC186 }187 // TODO memset(&distanceVector, 0, sizeof(distanceVector))188 M3.TerminalLastChangeTime = float64(common.TBtimestampNano()) // tiM3Now().String()189 changeState(StateDown)190 var bit uint64 = 0x1191 for j := 0; j < 64; j++ {192 // TODO .. from prev coded, should be just = 0xffffffffffffffff193 bit <<= 1194 }195 for m2Number := 0; m2Number < 4; m2Number++ {196 M3.Terminal[m2Number].TerminalMsgLastRcvdAt = time.Now() // TBtimestampNano() //time.Now()197 }198}199// InitM3Connectivity ================================================================200// Initialize IP and UDP addressing201//====================================================================================202func InitM3Connectivity() {203 M3.M3TerminalIPandPort = M3.M3TerminalIP + ":" + M3.M3TerminalPort204 var err3 error205 M3.TerminalUdpAddrStructure, err3 = net.ResolveUDPAddr("udp", M3.M3TerminalIPandPort)206 if err3 != nil {207 fmt.Println("ERROR ResolveUDPAddr: ", err3)208 } else {209 M3.M3TerminalFullName = common.NameId{Name: M3.M3TerminalName,210 Address: *M3.TerminalUdpAddrStructure}211 }212}213//====================================================================================214// Check if any err, and exit215//====================================================================================216func checkErrorNode(err error) {217 if err != nil {218 _, _ = fmt.Fprintf(os.Stderr, "Fatal error %s", err.Error())219 os.Exit(1)220 }221}222//====================================================================================223//224//====================================================================================225func periodicFunc(tick time.Time) {226 // TODO - figure out reasonable timer period to process these two227 // Note that we may have not receive messages from some terminals for some time228 // So maybe wait until the end of processing period and figure out who we229 // received discovery msgs from and based on that figure out the connectivity230 fmt.Println("TICK: UPDATE CONNECTIVITY ----- ", tick)231 currTimeMilliSec := common.TBtimestampMilli()232 for i := 1; i < 5; i++ {233 if M3.Terminal[i].TerminalActive == true {234 elapsedTimeSinceLastSend := currTimeMilliSec - M3.Terminal[i].TerminalLastHelloSendTime235 timeSinceLastHelloReceived := currTimeMilliSec - M3.Terminal[i].TerminalLastHelloReceiveTime236 if timeSinceLastHelloReceived > M3.TerminalHelloTimerLength {237 M3.Terminal[i].TerminalActive = false238 } else if elapsedTimeSinceLastSend >= M3.TerminalHelloTimerLength {239 M3.Terminal[i].TerminalLastHelloSendTime = currTimeMilliSec240 // send hello241 }242 }243 }244}245//===============================================================================246// M3 == Satellite, really M3247//===============================================================================248func main() {249 myOS := runtime.GOOS250 fmt.Println("========= M3 START on ", myOS, " at ", time.Now(), "==========")251 //===============================================================================252 // UPDATE RELEVANT VARIABLES and structures in proper order253 //===============================================================================254 InitM3Configuration()255 // Then try to read config file256 InitFromConfigFile()257 // Finally overwrite if any command arguments given258 InitFromCommandLine()259 M3.Terminal[0].TerminalActive = true // M1260 M3.Terminal[1].TerminalActive = false // M2 1261 M3.Terminal[2].TerminalActive = false // M2 2262 M3.Terminal[3].TerminalActive = false // M2 3263 M3.Terminal[4].TerminalActive = false // M2 4264 SetFinalM3Info()265 // Create LOG file266 common.CreateLog(&Log, M3.M3TerminalName, M3.TerminalLogPath)267 Log.Warning(&Log, "Warning test:this will be printed anyway")268 InitM3Connectivity()269 // Make this work one of these days ...270 var err error271 checkErrorNode(err)272 common.ControlPlaneInit(&(M3.Connectivity), M3.Channels)273 // START SEND AND RECEIVE THREADS:274 err2 := common.ControlPlaneRecvThread(&M3.Connectivity, M3.Channels)275 if err2 != nil {276 fmt.Println(M3.M3TerminalName, "INIT: Error creating Broadcast/Unicast RX thread")277 panic(err2)278 }279 // TODO: Make this work later280 //if M3.GroundIsKnown == true {281 // fmt.Println(M3.Name, ":",M3.FullName, "INIT: GROUND LOCATED")282 // changeState(StateConnected)283 // M3.KeepAliveRcvdTime = time.Now()284 //}285 //================================================================================286 // START TIMER : Call periodicFunc on every timerTick287 //================================================================================288 tick := 300 * time.Millisecond289 fmt.Println(M3.M3TerminalName, "MAIN: Starting a new Timer Ticker at ", tick, " msec")290 ticker := time.NewTicker(tick)291 go func() {292 for t := range ticker.C {293 //Call the periodic function here.294 periodicFunc(t)295 }296 }()297 //================================================================================298 // START CONSOLE:299 //================================================================================300 StartConsole(ConsoleInput)301 //================================================================================302 // RECEIVE AND PROCESS MESSAGES: Control Plane msgs, and Commands from console303 // Note that this software is implemented as FSM with run to completion304 //================================================================================305 for {306 select {307 case UnicastMsg := <-M3.Channels.UnicastRcvCtrlChannel:308 fmt.Println(M3.M3TerminalName, "MAIN: Unicast MSG in state", M3.M3TerminalState, "MSG=", string(UnicastMsg))309 // these include text messages from the ground/controller310 ControlPlaneMessages(UnicastMsg)311 case BroadcastMsg := <-M3.Channels.BroadcastRcvCtrlChannel:312 //fmt.Println(M3.M3Name, "MAIN: Broadcast MSG in state", M3.M3State, "MSG=",string(BroadcastMsg))313 // these include text messages from the ground/controller314 ControlPlaneMessages(BroadcastMsg)315 case MulticastMsg := <-M3.Channels.MulticastRcvCtrlChannel:316 //fmt.Println(M3.M3Name, "MAIN: Multicast MSG in state", M3.M3State, "MSG=",string(MulticastMsg))317 // these include text messages from the ground/controller318 ControlPlaneMessages(MulticastMsg)319 case CmdText, ok := <-ConsoleInput: // These are messsages from local M3 console320 fmt.Println("====> MAIN: Console Input: ", CmdText)321 if !ok {322 fmt.Println("ERROR Reading input from stdin:", CmdText)323 break324 } else {325 // fmt.Println("Read input from stdin:", CmdText)326 // LocalCommandMessages(CmdText)327 // SendTextMsg(stdin)328 // fmt.Println("Console input sent to ground");329 switch string(CmdText[0]) { // switch on console command330 case "status":331 fmt.Println("STATUS REPLY: Name=", M3.M3TerminalName, " State=", M3.M3TerminalState)332 }333 }334 //default:335 // fmt.Println("done and exit select")336 } // EndOfSelect337 } // EndOfFOR338 // common.ControlPlaneCloseConnections(M3.Connectivity)339 // os.Exit(0)340}341// ControlPlaneMessages ====================================================================================342// ControlPlaneMessages() - handle Control Plane messages343//====================================================================================344func ControlPlaneMessages(message []byte) {345 msg := new(common.Msg)346 err1 := common.TBunmarshal(message, &msg)347 if err1 != nil {348 println("Error unmarshalling message: ", msg.MsgHeader.MsgCode)349 return350 }351 msgHeader := &msg.MsgHeader352 sender := msgHeader.SrcId353 //msglen := len(message)354 fmt.Println("ControlPlaneMessages: Msg=", msg) //.MsgCode, " msglen=", msglen)355 // Was this msg originated by us ?356 if strings.Contains(msgHeader.SrcIP, M3.M3TerminalIP) && sender == M3.M3TerminalId {357 // println("My own message: MsgCode=", msgHeader.MsgCode, " M3.NodeId=", M3.NodeId)358 return359 }360 //============================================================================361 // Is the other side within the RF range ?362 // we need to do this for ethernet connectivity as we receive everything363 //============================================================================364 // First check that the senders id is in valid range365 if sender == M3.M3TerminalId || sender < 1 || sender > 5 {366 println("Sender id WRONG: ", sender, " MsgCode=", msgHeader.MsgCode)367 return368 }369 //node := &M3.NodeList[sender -1]370 fmt.Println("CHECK MESSAGE CODE ", msgHeader.MsgCode)371 switch msgHeader.MsgCode {372 case common.MSG_TYPE_DISCOVERY: // from another M3373 var discoveryMsg = new(common.MsgCodeDiscovery)374 err := common.TBunmarshal(message, discoveryMsg) //message375 if err != nil {376 println("ControlPlaneMessages: ERR=", err)377 return378 }379 ControlPlaneProcessDiscoveryMessage(msgHeader, &discoveryMsg.MsgDiscovery)380 break381 case common.MSG_TYPE_GROUND_INFO: // info from ground382 // TODO: will require some rethinking how to handle383 // TODO: may need to rebroadcast for nodes that aare out of range384 // Note that in order to cure the situation where a node might have been out of reach385 // at the time the STEP message was sent, GROUND will insert the latest value for386 //the StepMode in all GROUNDINFO messages .... but we need to process those ...387 handleGroundInfoMsg(msgHeader)388 break389 case common.MSG_TYPE_STATUS_REQ: // command from ground390 handleGroundStatusRequest(msgHeader)391 break392 case "UPDATE":393 break394 default:395 fmt.Println("ControlPlaneMessages: UNKNOWN Message")396 break397 }398}399//====================================================================================400// ControlPlaneMessage STATUS REQ401//====================================================================================402func handleGroundStatusRequest(msgHeader *common.MessageHeader) {403 fmt.Println("...... STATUS REQUEST: srcIP=", msgHeader.SrcIP, " SrcMAC=", msgHeader.SrcMAC,404 " DstID=", msgHeader.DstId, " SrcID=", msgHeader.SrcId)405 // REPLY406 sendUnicastStatusReplyPacket(msgHeader)407}408//====================================================================================409// ControlPlaneMessage GROUNDINFO410//====================================================================================411func handleGroundInfoMsg(msgHeader *common.MessageHeader) {412 var err error413 // TODO ... add to msg the playing field size .... hmmm ?? relation to random etc414 M3.GroundFullName.Name = msgHeader.SrcName //.DstName415 M3.GroundIP = msgHeader.SrcIP416 M3.GroundIPandPort = string(msgHeader.SrcIP) + ":" + msgHeader.SrcPort417 myPort, _ := strconv.Atoi(msgHeader.SrcPort)418 M3.GroundUdpPort = myPort419 M3.GroundIsKnown = true //msg.GroundUp420 // M3.GroundUdpAddrSTR.IP = msg.TxIP;421 //fmt.Println(TERMCOLOR, "... GROUNDINFO: Name=", M3.GroundFullName.Name,422 // " IP:Port=", M3.GroundIPandPort, " StepMode=", msgHeader.StepMode)423 // fmt.Println("Port=", msg.TxPort, " txIP=", msg.TxIP, " " +424 // "groundIP=",M3.GroundIP)425 M3.GroundUdpAddrSTR, err = net.ResolveUDPAddr("udp", M3.GroundIPandPort)426 //M3.GroundUdpAddrSTR.Port = msg.TxPort427 //M3.GroundUdpAddrSTR.IP = net.IP(msg.TxIP)428 //M3.GroundUdpAddrSTR.IP = net.IP((M3.GroundIP))429 //M3.GroundUdpAddrSTR.Port, _ = strconv.Atoi(M3.GroundUdpPort)430 //M3.GroundUdpAddrSTR.IP = M3.GroundIP // net.IP(M3.GroundIP)431 //fmt.Println("1 M3.GroundUdpAddrSTR=", M3.GroundUdpAddrSTR)432 myPort, _ = strconv.Atoi(msgHeader.DstPort)433 M3.GroundUdpAddrSTR = &net.UDPAddr{IP: net.ParseIP(msgHeader.DstIP), Port: myPort}434 M3.GroundFullName = common.NameId{Name: msgHeader.DstName, Address: *M3.GroundUdpAddrSTR}435 //fmt.Println("2 M3.GroundUdpAddrSTR=", M3.GroundUdpAddrSTR)436 if err != nil {437 fmt.Println("ERROR in net.ResolveUDPAddr = ", err)438 fmt.Println("ERROR locating master, will retry")439 return440 } else {441 // fmt.Println("GROUND INFO: Name=", M3.GroundFullName.Name, " IP:Port=", M3.GroundIPandPort)442 }443}444// ControlPlaneProcessDiscoveryMessage ===============================================445// Handle DISCOVERY messages in all states446//====================================================================================447func ControlPlaneProcessDiscoveryMessage(msgHeader *common.MessageHeader,448 discoveryMsg *common.DiscoveryMsgBody) {449 //fmt.Println("Discovery MSG in state ", M3.M3State)450 switch M3.M3TerminalState {451 case StateDown:452 stateConnectedDiscoveryMessage(msgHeader, discoveryMsg)453 break454 case StateConnecting:455 stateConnectedDiscoveryMessage(msgHeader, discoveryMsg)456 break457 case StateConnected:458 stateConnectedDiscoveryMessage(msgHeader, discoveryMsg)459 break460 default:461 }462}463//==========================================================================464// Me=0, M1=1, M2=2..5465//===========================================================================466func stateConnectedDiscoveryMessage(msgHeader *common.MessageHeader,467 discoveryMsg *common.DiscoveryMsgBody) {468 sender := msgHeader.SrcId469 // TODO ... make sure we only handle configured M1 and M2s470 if sender < 1 || sender > 5 {471 // fmt.Println("DISCARD MSG: invalid senderId=", sender)472 return473 }474 term := &M3.Terminal[sender-1]475 // update info for the sending terminal476 term.TerminalName = msgHeader.SrcName477 term.TerminalId = msgHeader.SrcId478 term.TerminalIP = msgHeader.SrcIP479 term.TerminalMac = msgHeader.SrcMAC480 term.TerminalPort = msgHeader.SrcPort481 term.TerminalNextMsgSeq = msgHeader.SrcSeq482 // Check if terminal was rebooted483 term.TerminalTimeCreated = discoveryMsg.TimeCreated // incarnation #484 term.TerminalLastChangeTime = discoveryMsg.LastChangeTime485 term.TerminalActive = discoveryMsg.NodeActive486 term.TerminalMsgsSent = discoveryMsg.MsgsSent487 term.TerminalMsgsRcvd = discoveryMsg.MsgsRcvd488 term.TerminalMsgLastSentAt = discoveryMsg.MsgLastSentAt489 term.TerminalMsgLastRcvdAt = time.Now() // TBtimestampNano() // time.Now()490 term.TerminalActive = true491 if M3.GroundIsKnown {492 // did this DISCOVERY reach the ground as well493 /*494 if node.NodeDistanceToGround > M3.GroundRadioRange {495 fmt.Println("=== NEED TO FORWARD, OTHER NODE ", int(node.NodeDistanceToGround),496 " AWAY FROM GROUND, Ground at ", M3.GroundRadioRange)497 theNode, distance := FindShortestConnectionToGround()498 fmt.Println("====== Me=", M3.NodeId, " MY DISTANCE=",M3.NodeDistanceToGround,499 " HIS DISTANCE=", node.NodeDistanceToGround," SHORTEST=", distance,500 " Forwarder=", theNode.NodeId)501 if Me == theNode && M3.NodeDistanceToGround <= M3.GroundRadioRange {502 fmt.Println("====== I AM THE FORWARDER ===========================")503 // forward the DISCOVERY as UNICAST to GROUND504 forwardUnicastDiscoveryPacket(msgHeader, discoveryMsg, int(distance))505 }506 } else {507 //fmt.Println("==NODE ", node.NodeId, " CAN REACH GROUND AT",node.DistanceToGround ,508 // " Ground at ", M3.GroundRadioRange)509 }510 */511 }512}513/*514func FindShortestConnectionToGround() (*common.NodeInfo, float64) {515 var theNode *common.NodeInfo = nil516 var distance float64 = 1000000000517 for j:=0; j<64; j++ {518 if M3.NodeList[j].NodeActive == true {519 if distance > M3.NodeList[j].NodeDistanceToGround {520 distance = M3.NodeList[j].NodeDistanceToGround521 theNode = &M3.NodeList[j]522 }523 }524 }525 return theNode, distance526}527//====================================================================================528// Handle messages received in the CONNECTED state529//====================================================================================530func RemoteCommandMessages(msg *common.Msg) {531 var cmds []common.LinuxCommand532 // _ = TBunmarshal(msg.MsgBody, &cmds)533 for cmdIndex := range cmds {534 var cmd common.LinuxCommand535 cmd = cmds[cmdIndex]536 err := RunLinuxCommand(REMOTE_CMD, cmd.Cmd, cmd.Par1, cmd.Par2, cmd.Par3, cmd.Par4, cmd.Par5, cmd.Par6)537 if err != nil {538 fmt.Printf("%T\n", err)539 }540 }541}542*/543//=======================================================================544//545//=======================================================================546func LocalCommandMessages(cmdText string) {547 //var cmd []string548 //cmd = strings.Split(cmdText, " ")549 switch cmdText {550 case "enable":551 M3.M3TerminalActive = true552 case "disable":553 M3.M3TerminalActive = false554 default:555 }556 fmt.Println("RCVD CONSOLE INPUT =", cmdText, " M3 ACTIVE=", M3.M3TerminalActive)557 // TODO figure out the bellow line558 //err := RunLinuxCommand(LOCAL_CMD, cmd[0], cmd[1], cmd[2], cmd[3], cmd[4], cmd[5], cmd[6])559 //if err != nil {fmt.Printf("%T\n", err)}560}561// RunLinuxCommand ========================================================562//563//=======================================================================564func RunLinuxCommand(origin, Cmd, Par1, Par2, Par3, Par4, Par5, Par6 string) error {565 //fmt.Println("RCVD CMD ", cmdIndex, " =",cmd)566 // fmt.Println("cmd=", cmd.Cmd, " ", cmd.Par1, " ", cmd.Par2, " ", cmd.Par3, " ", cmd.Par4, " ", cmd.Par5, " ", cmd.Par6)567 //cmd.Output() → run it, wait, get output568 //cmd.Run() → run it, wait for it to finish.569 //cmd.Start() → run it, don't wait. err = cmd.Wait() to get result.570 var thisCmd = exec.Command(Cmd, Par1, Par2, Par3, Par4, Par5, Par6)571 output, err := thisCmd.Output()572 //if err != nil && err.Error() != "exit status 1" {573 // fmt.Println("CMDx=", cmd.Cmd, " ", cmd.Par1, " ", cmd.Par2, " ", cmd.Par3, " ", cmd.Par4,574 // " ", cmd.Par5, " ", cmd.Par6, " : cmd.Run() failed with ", err)575 //} else {576 //if err != nil && err.Error() != "exit status 1" {577 // //panic(err)578 // //fmt.Printf("ERROR=", err, "\n")579 // fmt.Printf("%T\n", err)580 //} else {581 // fmt.Printf("CMD OUTPUT=",string(output))582 // // SEND REEPLY, OR MAYBE COMBINED ALL FIRST583 //}584 fmt.Println(origin, " CMD= ", Cmd, " ", Par1, Par2, " ", Par3, " ", Par4,585 " ", Par5, " ", Par6, " : RESULT:", string(output), " ERR:", err)586 return err587}588//====================================================================================589// Set new state590//====================================================================================591func changeState(newState string) {592 fmt.Println(M3.M3TerminalName, "OldState=", M3.M3TerminalState, " NewState=", newState)593 M3.M3TerminalState = newState594}595//====================================================================================596// Format and send DISCOVERY msg597//====================================================================================598func sendBroadcastDiscoveryPacket() {599 // ... done in updateConnectivity ...MoveNode(Me)600 //M3.TerminalMsgLastSentAt = float64(common.TBtimestampNano()) // time.Now() //TBtimestampNano()601 //strconv.FormatInt(TBtimestampNano(), 10)602 dstPort := M3.Connectivity.BroadcastTxPort603 // TODO add heightFromEarthCenter as configuration ?? what if it wobbles?604 // timeNow := tiM3.Now()605 msgHdr := common.MessageHeader{606 MsgCode: "DISCOVERY",607 Ttl: 3,608 TimeSent: float64(common.TBtimestampNano()), // timeNow, //M3.MsgLastSentAt, // time.Now().String()609 SrcSeq: M3.M3TerminalNextMsgSeq,610 SrcMAC: M3.M3TerminalMac,611 SrcName: M3.M3TerminalName,612 SrcId: M3.M3TerminalId, // node ids are 1 based613 SrcIP: M3.M3TerminalIP,614 SrcPort: M3.M3TerminalPort,615 DstName: "BROADCAST",616 DstId: 0,617 DstIP: M3.Connectivity.BroadcastTxIP,618 DstPort: dstPort,619 Hash: 0,620 }621 discBody := common.DiscoveryMsgBody{622 NodeActive: M3.M3TerminalActive,623 MsgsSent: M3.M3TerminalMsgsSent,624 MsgsRcvd: M3.M3TerminalMsgsRcvd,625 }626 myMsg := common.MsgCodeDiscovery{627 MsgHeader: msgHdr,628 MsgDiscovery: discBody,629 }630 M3.M3TerminalNextMsgSeq++631 msg, _ := common.TBmarshal(myMsg)632 // fmt.Println(" BROADCAST DISCOVERY", M3.BroadcastTxStruct)633 common.ControlPlaneBroadcastSend(M3.Connectivity, msg, M3.Connectivity.BroadcastTxStruct)634}635//=================================================================================636//=================================================================================637func sendUnicastStatusReplyPacket(msgHeader *common.MessageHeader) {638 fmt.Println("...... STATUS REPLY: srcIP=", msgHeader.SrcIP, " SrcMAC=", msgHeader.SrcMAC,639 " DstID=", msgHeader.DstId, " SrcID=", msgHeader.SrcId)640 // port, _ :=strconv.Atoi(M3.UnicastTxPort)641 // latitude,longitude := ConvertXYZtoLatLong(M3.MyX, M3.MyY, M3.MyZ, orbitHeightFromEartCenter)642 msgHdr := common.MessageHeader{643 MsgCode: "STATUS_REPLY",644 Ttl: 1,645 TimeSent: float64(common.TBtimestampNano()),646 SrcSeq: M3.M3TerminalNextMsgSeq,647 SrcMAC: M3.M3TerminalMac,648 SrcName: M3.M3TerminalName,649 SrcId: M3.M3TerminalId, // node ids are 1 based650 SrcIP: M3.M3TerminalIP,651 SrcPort: M3.M3TerminalPort,652 DstName: "UNICAST",653 DstId: msgHeader.SrcId,654 DstIP: msgHeader.SrcIP,655 DstPort: msgHeader.SrcPort,656 Hash: 0,657 }658 statusReplyBody := common.StatusReplyMsgBody{659 //TimeCreated: M3.TerminalTimeCreated,660 LastChangeTime: M3.TerminalLastChangeTime,661 NodeActive: M3.M3TerminalActive,662 MsgsSent: M3.M3TerminalMsgsSent,663 MsgsRcvd: M3.M3TerminalMsgsRcvd,664 //MsgLastSentAt: M3.TerminalMsgLastSentAt,665 }666 myMsg := common.MsgCodeStatusReply{667 MsgHeader: msgHdr,668 MsgStatusReply: statusReplyBody,669 }670 M3.M3TerminalNextMsgSeq++671 msg, _ := common.TBmarshal(myMsg)672 common.ControlPlaneUnicastSend(M3.Connectivity, msg, M3.GroundIP+":"+M3.Connectivity.UnicastTxPort)673}674//=================================================================================675//=================================================================================676func sendUnicastDiscoveryPacket(unicastIP string) {677 M3.M3TerminalMsgLastSentAt = float64(common.TBtimestampNano()) //time.Now()678 port := M3.Connectivity.UnicastTxPort // strconv.Atoi(M3.Connectivity.UnicastTxPort)679 // latitude,longitude := ConvertXYZtoLatLong(M3.MyX, M3.MyY, M3.MyZ, orbitHeightFromEartCenter)680 msgHdr := common.MessageHeader{681 MsgCode: "DISCOVERY",682 Ttl: 3,683 TimeSent: float64(common.TBtimestampNano()), // timeNow, //M3.MsgLastSentAt, // time.Now().String()684 SrcSeq: M3.M3TerminalNextMsgSeq,685 SrcMAC: M3.M3TerminalMac,686 SrcName: M3.M3TerminalName,687 SrcId: M3.M3TerminalId, // node ids are 1 based688 SrcIP: M3.M3TerminalIP,689 SrcPort: M3.M3TerminalPort,690 DstName: "UNICAST",691 DstId: 0,692 DstIP: M3.Connectivity.BroadcastTxIP,693 DstPort: port,694 Hash: 0,695 }696 discBody := common.DiscoveryMsgBody{697 NodeActive: M3.M3TerminalActive,698 MsgsSent: M3.M3TerminalMsgsSent,699 MsgsRcvd: M3.M3TerminalMsgsRcvd,700 }701 myMsg := common.MsgCodeDiscovery{702 MsgHeader: msgHdr,703 MsgDiscovery: discBody,704 }705 M3.M3TerminalNextMsgSeq++706 msg, _ := common.TBmarshal(myMsg)707 //fmt.Println( "SEND UNICAST DISCOVERY to ", unicastIP)708 common.ControlPlaneUnicastSend(M3.Connectivity, msg, unicastIP)709}710//====================================================================================711//712//====================================================================================713/*714 func getSize(v interface{}) int {715 size := int(reflect.TypeOf(v).Size())716 switch reflect.TypeOf(v).Kind() {717 case reflect.Slice:718 s := reflect.ValueOf(v)719 for i := 0; i < s.Len(); i++ {720 size += getSize(s.Index(i).Interface())721 }722 case reflect.Map:723 s := reflect.ValueOf(v)724 keys := s.MapKeys()725 size += int(float64(len(keys)) * 10.79) // approximation from https://golang.org/src/runtime/hashmap.go726 for i := range(keys) {727 size += getSize(keys[i].Interface()) + getSize(s.MapIndex(keys[i]).Interface())728 }729 case reflect.String:730 size += reflect.ValueOf(v).Len()731 case reflect.Struct:732 s := reflect.ValueOf(v)733 for i := 0; i < s.NumField(); i++ {734 if s.Field(i).CanInterface() {735 size += getSize(s.Field(i).Interface())736 }737 }738 }739 return size740 }741*/742//====================================================================================743// Check if we are talking to the ground/controller station744//====================================================================================745/*746 func isGroundKnown() bool {747 return M3.GroundIsKnown748 // NOTE that this will fail if M3.GroundUdpAddress has not been initialized due749 // to master not being up . Add state and try again to Resolve before doing this750 //var err error751 //fmt.Println("Locate master control, not ground")752 //M3.GroundUdpAddrSTR, err = net.ResolveUDPAddr("udp", M3.GroundIPandPort)753 //if err != nil {754 // fmt.Println("ERROR in net.ResolveUDPAddr = ", err)755 // fmt.Println("ERROR locating master, will retry")756 // return false757 //}758 // TODO check if this is needed759 //M3.GroundFullName = tbMessages.NameId{Name:M3.GroundIPandPort,OsId:0,TimeCreated:"0",Address:*M3.GroundUdpAddress}760 //fmt.Println(M3.M3Name, "INIT: masterFullName=", M3.GroundFullName)761 //mastersEntry := tbMessages.TBmgr{Name:M3.GroundFullName,Up:true,LastChangeTime:"0",MsgsSent:0,LastSentAt:"0",MsgsRcvd:0,LastRcvdAt:"0"}762 //M3.KnownM3s = append(M3.KnownM3s, mastersEntry)763 // fmt.Println("Records of Known Satellites=", M3.KnownM3s)764 // check the master is there:765 //theGround := locateOtherM3(M3.KnownM3s, M3.GroundIPandPort)766 //if theGround != nil {767 // fmt.Println("Ground at:", theGround.NodeName, "ADDRESS:", theGround.NodeIP, "Port:", theGround.NodePort,768 // "MSGSRCVD:", theGround.MsgsRcvd)769 //} else {770 // fmt.Println("GROUND Station Not Detected YET at ", M3.GroundIPandPort)771 //}772 //return true773 }774*/...

Full Screen

Full Screen

m2.go

Source:m2.go Github

copy

Full Screen

1//*********************************************************************************/2// Copyright 2017 www.igismo.com. All rights reserved. See open source license3// HISTORY:4// NAME REV DATE REMARKS @5// Goran Scuric 1.0 01012018 Initial design goran@usa.net by igismo6// Goran Scuric 2.0 09012019 Adapted for bifrost project7// Goran Scuric 3.0 12012020 Adapted for AeroMesh Space Mesh Networking8//=================================================================================9// COMMAND LINE OPTIONS:10// FORMAT: sudo ./drone [DroneName DroneId [myIP [myPort [groundIP [groundPort]]]]]11// use 0 anywhere for default12// EXAMPLE1: sudo ./aeroMeshNode DroneX 01 192.168.22.2 1201 192.168.1.1 120013//=================================================================================14// SYNAPSE VERSION15//================================================================================16/* UDPDaytimeClient17make function allocates and initializes an object of type slice, map, or chan only.18Like new, the first argument is a type. But, it can also take a second argument, the size.19Unlike new, make’s return type is the same as the type of its argument, not a pointer to it.20And the allocated value is initialized (not set to zero value like in new).21The reason is that slice, map and chan are data structures.22They need to be initialized, otherwise they won't be usable.23This is the reason new() and make() need to be different.24p := new(chan int) // p has type: *chan int25c := make(chan int) // c has type: chan int26p *[]int = new([]int) // *p = nil, which makes p useless27v []int = make([]int, 100) // creates v structure that has pointer to an array,28 length field, and capacity field. So, v is immediately usable29*/30package main31import (32 "fmt"33 "github.com/igismo/synapse/commonTB"34 "github.com/spf13/viper"35 "net"36 "os"37 "os/exec"38 "runtime"39 "strconv"40 "strings"41 "time"42)43//const DEBUG_ROLE = 044//const DEBUG_DISCOVERY = 045var M2 common.M2Info // all info about the Node46var Log = common.LogInstance{} // for log file storage47const StateDown = "DOWN"48const StateConnecting = "CONNECTING"49const StateConnected = "CONNECTED"50// REMOTE_CMD Command from local terminal, or rcvd from ground controller51// const LOCAL_CMD = "LOCAL"52const REMOTE_CMD = "REMOTE"53// InitM2Configuration InitDroneConfiguration ======================================54// READ ARGUMENTS IF ANY55//====================================================================================56func InitM2Configuration() {57 M2.M2TerminalName = "termM2A" // will be overwritten by config58 M2.M2TerminalId = 2 // will be overwritten by config59 M2.M2TerminalIP = ""60 M2.M2TerminalConnectionTimer = common.DRONE_KEEPALIVE_TIMER // 5 sec61 M2.M2Channels.CmdChannel = nil // so that all local threads can talk back62 M2.M2Channels.UnicastRcvCtrlChannel = nil // to send control msgs to Recv Thread63 M2.M2Channels.BroadcastRcvCtrlChannel = nil64 M2.M2Channels.MulticastRcvCtrlChannel = nil65 // M2.TerminalConnection = nil66 M2.M2TerminalReceiveCount = 067 M2.M2TerminalSendCount = 068 Log.DebugLog = true69 Log.WarningLog = true70 Log.ErrorLog = true71 M2.M2Channels.UnicastRcvCtrlChannel = make(chan []byte) //72 M2.M2Channels.BroadcastRcvCtrlChannel = make(chan []byte)73 M2.M2Channels.MulticastRcvCtrlChannel = make(chan []byte)74 M2.M2Channels.CmdChannel = make(chan []string) // receive command line cmnds75 M2.M2Connectivity.BroadcastRxAddress = ":48999"76 M2.M2Connectivity.BroadcastRxPort = "48999"77 M2.M2Connectivity.BroadcastRxIP = ""78 M2.M2Connectivity.BroadcastTxPort = "48888"79 M2.M2Connectivity.BroadcastConnection = nil80 M2.M2Connectivity.BroadcastTxStruct = new(net.UDPAddr)81 M2.M2Connectivity.UnicastRxAddress = ":48888"82 M2.M2Connectivity.UnicastRxPort = "48888"83 M2.M2Connectivity.UnicastRxIP = ""84 M2.M2Connectivity.UnicastTxPort = "48888"85 M2.M2Connectivity.UnicastConnection = nil86 M2.M2Connectivity.UnicastRxStruct = nil87 M2.M2Connectivity.UnicastTxStruct = new(net.UDPAddr)88 //M2.GroundIsKnown = false89 //M2.GroundUdpPort = 090 //M2.GroundIP = ""91 M2.M2TerminalPort = "8888"92 //M2.GroundIPandPort = "" //M2.GroundIP + ":" + M2.GroundUdpPort93 M2.M2TerminalUdpAddrStructure = new(net.UDPAddr)94 //M2.GroundUdpAddrSTR = new(net.UDPAddr)95 M2.M2TerminalTimeCreated = time.Now() // strconv.FormatInt(common.TBtimestampNano(), 10)96}97// InitFromConfigFile ================================================================98// InitFromConfigFile() - Set configuration from config file99//====================================================================================100func InitFromConfigFile() {101 var fileName string102 argNum := len(os.Args) // Number of arguments supplied, including the command103 fmt.Println("Number of Arguments = ", argNum)104 if argNum > 2 && os.Args[1] != "" && os.Args[1] != "0" {105 M2.M2TerminalName = os.Args[1]106 M2.M2TerminalId, _ = strconv.Atoi(os.Args[2])107 fileName = "config" + os.Args[2] + ".yml"108 viper.SetConfigName(fileName)109 } else {110 // Set the file name of the configurations file111 fileName = "config.yml"112 viper.SetConfigName(fileName)113 }114 // Set the path to look for the configurations file115 viper.AddConfigPath(".")116 // Enable VIPER to read Environment Variables117 viper.AutomaticEnv()118 viper.SetConfigType("yml")119 // var droneStruct DroneInfo120 if err := viper.ReadInConfig(); err != nil {121 fmt.Printf("Error reading config file, %s", err)122 return123 }124 // Set undefined variables125 viper.SetDefault("DroneName", "Drone1")126 // store configuration into the drone structure127 err := viper.Unmarshal(&M2) //&droneStruct)128 if err != nil {129 fmt.Printf("Unable to decode into struct, %v", err)130 }131 M2.M2Connectivity.UnicastRxIP = M2.M2UnicastRxIP132 M2.M2Connectivity.UnicastRxPort = M2.M2UnicastRxPort133 // M2.M2Connectivity.UnicastRxAddress =134 M2.M2Connectivity.UnicastTxPort = M2.M2UnicastTxPort135 M2.M2Connectivity.BroadcastTxIP = M2.M2BroadcastTxIP136 M2.M2Connectivity.BroadcastTxPort = M2.M2BroadcastTxPort137 // M2.M2Connectivity.BroadcastTxAddress =138 M2.M2Connectivity.BroadcastRxIP = M2.M2BroadcastRxIP139 M2.M2Connectivity.BroadcastRxPort = M2.M2BroadcastRxPort140 // M2.M2Connectivity.BroadcastRxAddress =141 M2.M3TerminalPort = M2.M2UnicastRxPort // Unless M3 tells are otherwise142 M2.M2Connectivity.BroadcastTxAddress =143 M2.M2Connectivity.BroadcastTxIP + ":" + M2.M2Connectivity.BroadcastTxPort144 M2.M2Connectivity.BroadcastRxAddress =145 M2.M2Connectivity.BroadcastRxIP + ":" + M2.M2Connectivity.BroadcastRxPort146 M2.M2Connectivity.UnicastRxAddress =147 M2.M2Connectivity.UnicastRxIP + ":" + M2.M2Connectivity.UnicastRxPort148 fmt.Println("Reading variables from ... config", fileName)149 fmt.Println("*************************************************************")150 fmt.Println("M2TerminalId = ", M2.M2TerminalId)151 fmt.Println("M2TerminalName = ", M2.M2TerminalName)152 fmt.Println("M2TerminalIP = ", M2.M2TerminalIP)153 fmt.Println("M2TerminalLogPath = ", M2.M2TerminalLogPath)154 fmt.Println("TerminalConnectionTimer = ", M2.M2TerminalConnectionTimer)155 fmt.Println("M2TerminalPort = ", M2.M2TerminalPort)156 fmt.Println("BroadcastTxIP = ", M2.M2Connectivity.BroadcastTxIP)157 fmt.Println("BroadcastTxPort = ", M2.M2Connectivity.BroadcastTxPort)158 fmt.Println("BroadcastRxIP = ", M2.M2Connectivity.BroadcastRxIP)159 fmt.Println("BroadcastRxPort = ", M2.M2Connectivity.BroadcastRxPort)160 fmt.Println("BroadcastRxAddress = ", M2.M2Connectivity.BroadcastRxAddress)161 fmt.Println("BroadcastTxAddress = ", M2.M2Connectivity.BroadcastTxAddress)162 fmt.Println("UnicastRxIP = ", M2.M2Connectivity.UnicastRxIP)163 fmt.Println("UnicastRxPort = ", M2.M2Connectivity.UnicastRxPort)164 fmt.Println("UnicastRxAddress = ", M2.M2Connectivity.UnicastRxAddress)165 fmt.Println("M3TerminalIP = ", M2.M3TerminalIP)166 fmt.Println("M3TerminalPort = ", M2.M3TerminalPort)167}168// InitFromCommandLine ====================================================================================169// InitFromCommandLine() READ ARGUMENTS IF ANY170//====================================================================================171func InitFromCommandLine() {172 // argsWithProg := os.Args; argsWithoutProg := os.Args[1:]173 // Second: check for the command line parametersz, they overwrite the config file174 for index := range os.Args {175 arg := os.Args[index]176 fmt.Println("Arg", index, "=", arg)177 }178 argNum := len(os.Args) // Number of arguments supplied, including the command179 fmt.Println("Number of Arguments = ", argNum)180 if argNum > 2 && os.Args[1] != "" && os.Args[1] != "0" {181 fmt.Println("M2 NAME = ", os.Args[1])182 M2.M2TerminalName = os.Args[1]183 M2.M2TerminalId, _ = strconv.Atoi(os.Args[2])184 }185 if argNum > 3 && os.Args[3] != "" && os.Args[3] != "0" {186 fmt.Println("Satellite IP = ", os.Args[3])187 M2.M2TerminalIP = os.Args[3]188 // TODO: Set eth0 IP address to M2.M2IpAddress !!!189 var ifCmd = exec.Command("sudo", "ifconfig", "eth0",190 M2.M2TerminalIP, "up", "", "")191 output, err := ifCmd.Output()192 fmt.Println("SET MY IP=", "sudo", "ifconfig", "eth0", M2.M2TerminalIP, "up",193 " -OUTPUT:", string(output), " ERR:", err)194 }195 if argNum > 4 && os.Args[4] != "" && os.Args[4] != "0" {196 M2.M2TerminalPort = os.Args[4] // strconv.ParseInt(os.Args[3], 10, 64)197 }198 if argNum > 5 && os.Args[5] != "" && os.Args[5] != "0" && argNum > 6 && os.Args[6] != "" && os.Args[6] != "0" {199 // M2.GroundIPandPort = os.Args[5] + ":" + os.Args[6]200 }201}202// SetFinalM2Info ===============================================================203// Initialize my own info in the M2 structure204//===============================================================================205func SetFinalM2Info() {206 fmt.Println("SetFinalM2Info ")207 if M2.M2TerminalIP == "" {208 M2.M2TerminalIP, M2.M2TerminalMac = common.GetLocalIp() // get IP and MAC209 fmt.Println("M2 Local IP=", M2.M2TerminalIP, " MAC=", M2.M2TerminalMac)210 }211 M2.M2TerminalLastChangeTime = float64(common.TBtimestampNano()) // timeNow().String()212 changeState(StateDown)213}214// InitM2Connectivity ================================================================215// Initialize IP and UDP addressing216//====================================================================================217func InitM2Connectivity() {218 M2.M2TerminalIPandPort = M2.M2TerminalIP + ":" + M2.M2TerminalPort219 var err3 error220 M2.M2TerminalUdpAddrStructure, err3 = net.ResolveUDPAddr("udp", M2.M2TerminalIPandPort)221 if err3 != nil {222 fmt.Println("ERROR ResolveUDPAddr: ", err3)223 } else {224 M2.M2TerminalFullName = common.NameId{Name: M2.M2TerminalName,225 Address: *M2.M2TerminalUdpAddrStructure}226 }227}228//====================================================================================229// Check if any err, and exit230//====================================================================================231func checkErrorNode(err error) {232 if err != nil {233 _, _ = fmt.Fprintf(os.Stderr, "Fatal error %s", err.Error())234 os.Exit(1)235 }236}237//====================================================================================238//239//====================================================================================240func periodicFunc(tick time.Time) {241 // TODO - figure out reasonable timer period to process these two242 // Note that we may have not receive messages from some terminals for some time243 // So maybe wait until the end of processing period and figure out who we244 // received discovery msgs from and based on that figure out the connectivity245 fmt.Println("TICK: UPDATE CONNECTIVITY ----- ", tick)246 currTimeMilliSec := common.TBtimestampMilli()247 elapsedTimeSinceLastHelloSent := currTimeMilliSec - M2.M2TerminalLastHelloSendTime248 elapsedTimeSinceLastHelloReceived := currTimeMilliSec - M2.M2TerminalLastHelloReceiveTime249 if elapsedTimeSinceLastHelloReceived > M2.M2TerminalHelloTimerLength {250 // No word from M3 fro a long time, resend our hello251 sendBroadcastHelloPacket()252 M2.M2TerminalLastHelloSendTime = common.TBtimestampMilli()253 changeState(StateConnecting)254 } else if elapsedTimeSinceLastHelloSent > M2.M2TerminalHelloTimerLength {255 // time to resend our hello, in either connecting or connected state256 sendUnicastHelloPacket(M2.M3TerminalIP, M2.M3TerminalPort)257 M2.M2TerminalLastHelloSendTime = common.TBtimestampMilli()258 }259}260//===============================================================================261// M2 == Satellite, really M2262//===============================================================================263func main() {264 myOS := runtime.GOOS265 fmt.Println(M2.M2TerminalName, " ========= START on ", myOS, " at ", time.Now(), "==========")266 //===============================================================================267 // UPDATE RELEVANT VARIABLES and structures in proper order268 //===============================================================================269 InitM2Configuration()270 // Then try to read config file271 InitFromConfigFile()272 // Finally overwrite if any command arguments given273 InitFromCommandLine()274 SetFinalM2Info()275 // Create LOG file276 common.CreateLog(&Log, M2.M2TerminalName, M2.M2TerminalLogPath)277 Log.Warning(&Log, "Warning test:this will be printed anyway")278 InitM2Connectivity()279 // Make this work one of these days ...280 var err error281 checkErrorNode(err)282 common.ControlPlaneInit(&M2.M2Connectivity, M2.M2Channels)283 // START SEND AND RECEIVE THREADS:284 err2 := common.ControlPlaneRecvThread(&M2.M2Connectivity, M2.M2Channels)285 if err2 != nil {286 fmt.Println(M2.M2TerminalName, "INIT: Error creating Broadcast/Unicast RX thread")287 panic(err2)288 }289 //================================================================================290 // START TIMER : Call periodicFunc on every timerTick291 //================================================================================292 tick := 3000 * time.Millisecond293 fmt.Println(M2.M2TerminalName, "MAIN: Starting a new Timer Ticker at ", tick, " msec")294 ticker := time.NewTicker(tick)295 go func() {296 for t := range ticker.C {297 //Call the periodic function here.298 periodicFunc(t)299 }300 }()301 //================================================================================302 // START CONSOLE:303 //================================================================================304 StartConsole(ConsoleInput)305 //================================================================================306 // RECEIVE AND PROCESS MESSAGES: Control Plane msgs, and Commands from console307 // Note that this software is implemented as FSM with run to completion308 //================================================================================309 for {310 fmt.Println("------------------------------------------------------------------")311 select {312 case UnicastMsg := <-M2.M2Channels.UnicastRcvCtrlChannel:313 fmt.Println(M2.M2TerminalName, "====> MAIN: Unicast MSG in state", M2.M2TerminalState, "MSG=", string(UnicastMsg))314 // these include text messages from the ground/controller315 ControlPlaneMessages(UnicastMsg)316 case BroadcastMsg := <-M2.M2Channels.BroadcastRcvCtrlChannel:317 fmt.Println(M2.M2TerminalName, "====> MAIN: Broadcast MSG in state", M2.M2TerminalState, "MSG=", string(BroadcastMsg))318 // these include text messages from the ground/controller319 ControlPlaneMessages(BroadcastMsg)320 case MulticastMsg := <-M2.M2Channels.MulticastRcvCtrlChannel:321 fmt.Println(M2.M2TerminalName, "====> MAIN: Multicast MSG in state", M2.M2TerminalState, "MSG=", string(MulticastMsg))322 // these include text messages from the ground/controller323 ControlPlaneMessages(MulticastMsg)324 case CmdText, ok := <-ConsoleInput: // These are messsages from local M2 console325 fmt.Println(M2.M2TerminalName, "====> MAIN: Console Input: ", CmdText)326 if !ok {327 fmt.Println("ERROR Reading input from stdin:", CmdText)328 break329 } else {330 // INPUT, cmd and parameters are separated in CmdText[] string,331 // PROCESS / PARSE332 //fmt.Println("Console: SEND Unicast Packet, stdin:", CmdText)333 //sendUnicastHelloPacket(ip, port)334 // SendTextMsg(stdin)335 // fmt.Println("Console input sent to ground");336 switch CmdText[0] { // switch on console command337 case "status":338 fmt.Println("STATUS REPLY: Name=", M2.M2TerminalName, " State=", M2.M2TerminalState)339 }340 }341 //default:342 // fmt.Println("done and exit select")343 } // EndOfSelect344 } // EndOfFOR345 // common.ControlPlaneCloseConnections(M2.Connectivity)346 // os.Exit(0)347}348// ControlPlaneMessages ====================================================================================349// ControlPlaneMessages() - handle Control Plane messages350//====================================================================================351func ControlPlaneMessages(message []byte) {352 msg := new(common.Msg)353 err1 := common.TBunmarshal(message, &msg)354 if err1 != nil {355 println("Error unmarshalling message: ", msg.MsgHeader.MsgCode)356 return357 }358 msgHeader := &msg.MsgHeader359 sender := msgHeader.SrcId360 //msglen := len(message)361 //fmt.Println("ControlPlaneMessages: Msg=", msg) //.MsgCode, " msglen=", msglen)362 // Was this msg originated by us ?363 if strings.Contains(msgHeader.SrcIP, M2.M2TerminalIP) && sender == M2.M2TerminalId {364 // println("My own message: MsgCode=", msgHeader.MsgCode, " M2.NodeId=", M2.NodeId)365 return366 }367 //============================================================================368 // Is the other side within the RF range ?369 // we need to do this for ethernet connectivity as we receive everything370 //============================================================================371 // First check that the senders id is in valid range372 if sender == M2.M2TerminalId || sender < 1 || sender > 5 {373 println("Sender id WRONG: ", sender, " MsgCode=", msgHeader.MsgCode)374 return375 }376 //node := &M2.NodeList[sender -1]377 fmt.Println("CHECK MESSAGE CODE ", msgHeader.MsgCode)378 switch msgHeader.MsgCode {379 case common.MSG_TYPE_DISCOVERY: // from another M2380 var discoveryMsg = new(common.MsgCodeDiscovery)381 err := common.TBunmarshal(message, discoveryMsg) //message382 if err != nil {383 println("ControlPlaneMessages: ERR=", err)384 return385 }386 ControlPlaneProcessDiscoveryMessage(msgHeader, &discoveryMsg.MsgDiscovery)387 break388 case common.MSG_TYPE_GROUND_INFO: // info from ground389 // TODO: will require some rethinking how to handle390 // TODO: may need to rebroadcast for nodes that aare out of range391 // Note that in order to cure the situation where a node might have been out of reach392 // at the time the STEP message was sent, GROUND will insert the latest value for393 //the StepMode in all GROUNDINFO messages .... but we need to process those ...394 handleGroundInfoMsg(msgHeader)395 break396 case common.MSG_TYPE_STATUS_REQ: // command from ground397 handleGroundStatusRequest(msgHeader)398 break399 case "UPDATE":400 break401 default:402 fmt.Println("ControlPlaneMessages: UNKNOWN Message")403 break404 }405}406//====================================================================================407// ControlPlaneMessage STATUS REQ408//====================================================================================409func handleGroundStatusRequest(msgHeader *common.MessageHeader) {410 fmt.Println("...... STATUS REQUEST: srcIP=", msgHeader.SrcIP, " SrcMAC=", msgHeader.SrcMAC,411 " DstID=", msgHeader.DstId, " SrcID=", msgHeader.SrcId)412 // REPLY413 sendUnicastStatusReplyPacket(msgHeader)414}415//====================================================================================416// ControlPlaneMessage GROUNDINFO417//====================================================================================418func handleGroundInfoMsg(msgHeader *common.MessageHeader) {419 /*420 var err error421 // TODO ... add to msg the playing field size .... hmmm ?? relation to random etc422 M2.GroundFullName.Name = msgHeader.SrcName //.DstName423 M2.GroundIP = msgHeader.SrcIP424 M2.GroundIPandPort = string(msgHeader.SrcIP) + ":" + msgHeader.SrcPort425 myPort, _ := strconv.Atoi(msgHeader.SrcPort)426 M2.GroundUdpPort = myPort427 M2.GroundIsKnown = true //msg.GroundUp428 // M2.GroundUdpAddrSTR.IP = msg.TxIP;429 //fmt.Println(TERMCOLOR, "... GROUNDINFO: Name=", M2.GroundFullName.Name,430 // " IP:Port=", M2.GroundIPandPort, " StepMode=", msgHeader.StepMode)431 // fmt.Println("Port=", msg.TxPort, " txIP=", msg.TxIP, " " +432 // "groundIP=",M2.GroundIP)433 M2.GroundUdpAddrSTR, err = net.ResolveUDPAddr("udp", M2.GroundIPandPort)434 //M2.GroundUdpAddrSTR.Port = msg.TxPort435 //M2.GroundUdpAddrSTR.IP = net.IP(msg.TxIP)436 //M2.GroundUdpAddrSTR.IP = net.IP((M2.GroundIP))437 //M2.GroundUdpAddrSTR.Port, _ = strconv.Atoi(M2.GroundUdpPort)438 //M2.GroundUdpAddrSTR.IP = M2.GroundIP // net.IP(M2.GroundIP)439 //fmt.Println("1 M2.GroundUdpAddrSTR=", M2.GroundUdpAddrSTR)440 myPort, _ = strconv.Atoi(msgHeader.DstPort)441 M2.GroundUdpAddrSTR = &net.UDPAddr{IP: net.ParseIP(msgHeader.DstIP), Port: myPort}442 M2.GroundFullName = common.NameId{Name: msgHeader.DstName, Address: *M2.GroundUdpAddrSTR}443 //fmt.Println("2 M2.GroundUdpAddrSTR=", M2.GroundUdpAddrSTR)444 if err != nil {445 fmt.Println("ERROR in net.ResolveUDPAddr = ", err)446 fmt.Println("ERROR locating master, will retry")447 return448 } else {449 // fmt.Println("GROUND INFO: Name=", M2.GroundFullName.Name, " IP:Port=", M2.GroundIPandPort)450 }451 */452}453// ControlPlaneProcessDiscoveryMessage ===============================================454// Handle DISCOVERY messages in all states455//====================================================================================456func ControlPlaneProcessDiscoveryMessage(msgHeader *common.MessageHeader,457 // TODO: handle unicast and broadcast separatelly ??458 discoveryMsg *common.DiscoveryMsgBody) {459 //fmt.Println("Discovery MSG in state ", M2.M2State)460 switch M2.M2TerminalState {461 case StateDown:462 stateConnectedHelloMessage(msgHeader, discoveryMsg)463 break464 case StateConnecting:465 stateConnectedHelloMessage(msgHeader, discoveryMsg)466 break467 case StateConnected:468 stateConnectedHelloMessage(msgHeader, discoveryMsg)469 break470 default:471 }472}473//==========================================================================474// Me=0, M1=1, M2=2..5475//===========================================================================476func stateConnectedHelloMessage(msgHeader *common.MessageHeader,477 discoveryMsg *common.DiscoveryMsgBody) {478 sender := msgHeader.SrcId479 // TODO ... make sure we only handle configured M1 and M2s480 if sender < 1 || sender > 5 {481 // fmt.Println("DISCARD MSG: invalid senderId=", sender)482 return483 }484 M2.M2TerminalMsgLastSentAt = discoveryMsg.MsgLastSentAt485 M2.M2TerminalLastHelloReceiveTime = common.TBtimestampNano() // time.Now()486 /*487 if M2.GroundIsKnown {488 // did this DISCOVERY reach the ground as well489 if node.NodeDistanceToGround > M2.GroundRadioRange {490 fmt.Println("=== NEED TO FORWARD, OTHER NODE ", int(node.NodeDistanceToGround),491 " AWAY FROM GROUND, Ground at ", M2.GroundRadioRange)492 theNode, distance := FindShortestConnectionToGround()493 fmt.Println("====== Me=", M2.NodeId, " MY DISTANCE=",M2.NodeDistanceToGround,494 " HIS DISTANCE=", node.NodeDistanceToGround," SHORTEST=", distance,495 " Forwarder=", theNode.NodeId)496 if Me == theNode && M2.NodeDistanceToGround <= M2.GroundRadioRange {497 fmt.Println("====== I AM THE FORWARDER ===========================")498 // forward the DISCOVERY as UNICAST to GROUND499 forwardUnicastDiscoveryPacket(msgHeader, discoveryMsg, int(distance))500 }501 } else {502 //fmt.Println("==NODE ", node.NodeId, " CAN REACH GROUND AT",node.DistanceToGround ,503 // " Ground at ", M2.GroundRadioRange)504 }505 }506 */507}508/*509func FindShortestConnectionToGround() (*common.NodeInfo, float64) {510 var theNode *common.NodeInfo = nil511 var distance float64 = 1000000000512 for j:=0; j<64; j++ {513 if M2.NodeList[j].NodeActive == true {514 if distance > M2.NodeList[j].NodeDistanceToGround {515 distance = M2.NodeList[j].NodeDistanceToGround516 theNode = &M2.NodeList[j]517 }518 }519 }520 return theNode, distance521}522//====================================================================================523// Handle messages received in the CONNECTED state524//====================================================================================525func RemoteCommandMessages(msg *common.Msg) {526 var cmds []common.LinuxCommand527 // _ = TBunmarshal(msg.MsgBody, &cmds)528 for cmdIndex := range cmds {529 var cmd common.LinuxCommand530 cmd = cmds[cmdIndex]531 err := RunLinuxCommand(REMOTE_CMD, cmd.Cmd, cmd.Par1, cmd.Par2, cmd.Par3, cmd.Par4, cmd.Par5, cmd.Par6)532 if err != nil {533 fmt.Printf("%T\n", err)534 }535 }536}537*/538//=======================================================================539//540//=======================================================================541func LocalCommandMessages(cmdText string) {542 //var cmd []string543 //cmd = strings.Split(cmdText, " ")544 switch cmdText {545 case "enable":546 M2.M2TerminalActive = true547 case "disable":548 M2.M2TerminalActive = false549 case "help":550 fmt.Println("MAIN ......... No Help yet")551 default:552 }553 //fmt.Println("RCVD CONSOLE INPUT =", cmdText, " M2 ACTIVE=", M2.M2TerminalActive)554 // TODO figure out the bellow line555 //err := RunLinuxCommand(LOCAL_CMD, cmd[0], cmd[1], cmd[2], cmd[3], cmd[4], cmd[5], cmd[6])556 //if err != nil {fmt.Printf("%T\n", err)}557}558// RunLinuxCommand ========================================================559//560//=======================================================================561func RunLinuxCommand(origin, Cmd, Par1, Par2, Par3, Par4, Par5, Par6 string) error {562 //fmt.Println("RCVD CMD ", cmdIndex, " =",cmd)563 // fmt.Println("cmd=", cmd.Cmd, " ", cmd.Par1, " ", cmd.Par2, " ", cmd.Par3, " ", cmd.Par4, " ", cmd.Par5, " ", cmd.Par6)564 //cmd.Output() → run it, wait, get output565 //cmd.Run() → run it, wait for it to finish.566 //cmd.Start() → run it, don't wait. err = cmd.Wait() to get result.567 var thisCmd = exec.Command(Cmd, Par1, Par2, Par3, Par4, Par5, Par6)568 output, err := thisCmd.Output()569 //if err != nil && err.Error() != "exit status 1" {570 // fmt.Println("CMDx=", cmd.Cmd, " ", cmd.Par1, " ", cmd.Par2, " ", cmd.Par3, " ", cmd.Par4,571 // " ", cmd.Par5, " ", cmd.Par6, " : cmd.Run() failed with ", err)572 //} else {573 //if err != nil && err.Error() != "exit status 1" {574 // //panic(err)575 // //fmt.Printf("ERROR=", err, "\n")576 // fmt.Printf("%T\n", err)577 //} else {578 // fmt.Printf("CMD OUTPUT=",string(output))579 // // SEND REEPLY, OR MAYBE COMBINED ALL FIRST580 //}581 fmt.Println(origin, " CMD= ", Cmd, " ", Par1, Par2, " ", Par3, " ", Par4,582 " ", Par5, " ", Par6, " : RESULT:", string(output), " ERR:", err)583 return err584}585//====================================================================================586// Set new state587//====================================================================================588func changeState(newState string) {589 fmt.Println(M2.M2TerminalName, "OldState=", M2.M2TerminalState, " NewState=", newState)590 M2.M2TerminalState = newState591}592//====================================================================================593// Format and send DISCOVERY msg594//====================================================================================595func sendBroadcastHelloPacket() {596 dstPort := M2.M2Connectivity.BroadcastTxPort597 msgHdr := common.MessageHeader{598 MsgCode: "DISCOVERY",599 Ttl: 3,600 TimeSent: float64(common.TBtimestampNano()), // timeNow, //M2.MsgLastSentAt, // time.Now().String()601 SrcSeq: M2.M2TerminalNextMsgSeq,602 SrcMAC: M2.M2TerminalMac,603 SrcName: M2.M2TerminalName,604 SrcId: M2.M2TerminalId, // node ids are 1 based605 SrcIP: M2.M2TerminalIP,606 SrcPort: M2.M2TerminalPort,607 DstName: "BROADCAST",608 DstId: 0,609 DstIP: M2.M2Connectivity.BroadcastTxIP,610 DstPort: dstPort,611 Hash: 0,612 }613 discBody := common.DiscoveryMsgBody{614 NodeActive: M2.M2TerminalActive,615 MsgsSent: M2.M2TerminalMsgsSent,616 MsgsRcvd: M2.M2TerminalMsgsRcvd,617 }618 myMsg := common.MsgCodeDiscovery{619 MsgHeader: msgHdr,620 MsgDiscovery: discBody,621 }622 M2.M2TerminalNextMsgSeq++623 msg, _ := common.TBmarshal(myMsg)624 fmt.Println("SEND BROADCAST DISCOVERY", M2.M2Connectivity.BroadcastTxStruct)625 if M2.M2Connectivity.BroadcastConnection != nil {626 common.ControlPlaneBroadcastSend(M2.M2Connectivity, msg, M2.M2Connectivity.BroadcastTxStruct)627 } else {628 // TODO complain629 }630}631//=================================================================================632//=================================================================================633func sendUnicastStatusReplyPacket(msgHeader *common.MessageHeader) {634 fmt.Println("...... STATUS REPLY: srcIP=", msgHeader.SrcIP, " SrcMAC=", msgHeader.SrcMAC,635 " DstID=", msgHeader.DstId, " SrcID=", msgHeader.SrcId)636 /*637 // port, _ :=strconv.Atoi(M2.UnicastTxPort)638 // latitude,longitude := ConvertXYZtoLatLong(M2.MyX, M2.MyY, M2.MyZ, orbitHeightFromEartCenter)639 msgHdr := common.MessageHeader{640 MsgCode: "STATUS_REPLY",641 Ttl: 1,642 TimeSent: float64(common.TBtimestampNano()),643 SrcSeq: M2.M2TerminalNextMsgSeq,644 SrcMAC: M2.M2TerminalMac,645 SrcName: M2.M2TerminalName,646 SrcId: M2.M2TerminalId, // node ids are 1 based647 SrcIP: M2.M2TerminalIP,648 SrcPort: M2.M2TerminalPort,649 DstName: "UNICAST",650 DstId: msgHeader.SrcId,651 DstIP: msgHeader.SrcIP,652 DstPort: msgHeader.SrcPort,653 Hash: 0,654 }655 statusReplyBody := common.StatusReplyMsgBody{656 //TimeCreated: M2.TerminalTimeCreated,657 LastChangeTime: M2.M2TerminalLastChangeTime,658 NodeActive: M2.M2TerminalActive,659 MsgsSent: M2.M2TerminalMsgsSent,660 MsgsRcvd: M2.M2TerminalMsgsRcvd,661 //MsgLastSentAt: M2.TerminalMsgLastSentAt,662 }663 myMsg := common.MsgCodeStatusReply{664 MsgHeader: msgHdr,665 MsgStatusReply: statusReplyBody,666 }667 M2.M2TerminalNextMsgSeq++668 msg, _ := common.TBmarshal(myMsg)669 common.ControlPlaneUnicastSend(M2.M2Connectivity, msg, M2.GroundIP+":"+M2.Connectivity.UnicastTxPort)670 */671}672//=================================================================================673//=================================================================================674func sendUnicastHelloPacket(unicastIP, port string) {675 M2.M2TerminalMsgLastSentAt = float64(common.TBtimestampNano()) //time.Now()676 msgHdr := common.MessageHeader{677 MsgCode: "DISCOVERY",678 Ttl: 3,679 TimeSent: float64(common.TBtimestampNano()), // timeNow, //M2.MsgLastSentAt, // time.Now().String()680 SrcSeq: M2.M2TerminalNextMsgSeq,681 SrcMAC: M2.M2TerminalMac,682 SrcName: M2.M2TerminalName,683 SrcId: M2.M2TerminalId, // node ids are 1 based684 SrcIP: M2.M2TerminalIP,685 SrcPort: M2.M2TerminalPort,686 DstName: "UNICAST",687 DstId: 0,688 DstIP: unicastIP, //M2.M2Connectivity.BroadcastTxIP,689 DstPort: port,690 Hash: 0,691 }692 discBody := common.DiscoveryMsgBody{693 NodeActive: M2.M2TerminalActive,694 MsgsSent: M2.M2TerminalMsgsSent,695 MsgsRcvd: M2.M2TerminalMsgsRcvd,696 }697 myMsg := common.MsgCodeDiscovery{698 MsgHeader: msgHdr,699 MsgDiscovery: discBody,700 }701 M2.M2TerminalNextMsgSeq++702 msg, _ := common.TBmarshal(myMsg)703 fmt.Println("SEND UNICAST DISCOVERY to ", unicastIP)704 common.ControlPlaneUnicastSend(M2.M2Connectivity, msg, M2.M3TerminalIP)705}...

Full Screen

Full Screen

main.go

Source:main.go Github

copy

Full Screen

...14}15func Start() {16 dataFolder := "./data"17 configFileName := "config.yaml"18 tokenString := initFromConfigFile(filepath.Join(dataFolder, configFileName))19 token, err := auth.ParseUrlString(tokenString)20 if err != nil {21 log.Fatal(fmt.Errorf("error parsing token: %v", err))22 }23 vk := client.NewVk(token)24 //vk.ListFriends()25 vk.RemoveDeletedFriends()26 //vk.AddFriend(155633421)27 //vk.AddFriend(28421522)28 //vk.DeleteFriend(2916112)29 //vk.DeleteFriend(28421522)30}31func initFromConfigFile(pathToConfig string) (tokenUrl string) {32 err := tools.ReadConfig(pathToConfig)33 if err != nil {34 log.Fatal(err)35 }36 clientId := viper.GetString("clientId")37 if clientId == "" {38 log.Fatal(fmt.Errorf("confing file %v has error: clientId not found", pathToConfig))39 }40 tokenUrl = viper.GetString("tokenUrl")41 if tokenUrl == "" {42 requestToken(clientId, pathToConfig)43 }44 return45}...

Full Screen

Full Screen

initFromConfigFile

Using AI Code Generation

copy

Full Screen

1func main() {2 run := new(run)3 run.initFromConfigFile("config.json")4}5func main() {6 run := new(run)7 run.initFromConfigFile("config.json")8}9func main() {10 run := new(run)11 run.initFromConfigFile("config.json")12}13func main() {14 run := new(run)15 run.initFromConfigFile("config.json")16}17func main() {18 run := new(run)19 run.initFromConfigFile("config.json")20}21func main() {22 run := new(run)23 run.initFromConfigFile("config.json")24}25func main() {26 run := new(run)27 run.initFromConfigFile("config.json")28}29func main() {30 run := new(run)31 run.initFromConfigFile("config.json")32}33func main() {34 run := new(run)35 run.initFromConfigFile("config.json")36}37func main() {38 run := new(run)39 run.initFromConfigFile("config.json")40}41func main() {42 run := new(run)43 run.initFromConfigFile("config.json")44}45func main() {46 run := new(run)47 run.initFromConfigFile("config.json")48}49func main() {

Full Screen

Full Screen

initFromConfigFile

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 app := cli.NewApp()4 app.Action = func(c *cli.Context) error {5 fmt.Println("Hello friend!")6 }7 app.Commands = []cli.Command{8 {9 Action: func(c *cli.Context) error {10 fmt.Println("initialize the container")11 cmd := exec.Command("sh", "-c", "mkdir rootfs && cd rootfs && mkdir bin etc dev proc sys tmp var && cd .. && mkdir -p /tmp/containers/runC/rootfs && mkdir workdir")12 cmd.Run()13 },14 },15 {16 Action: func(c *cli.Context) error {17 fmt.Println("start a container")18 cmd := exec.Command("sh", "-c", "cd rootfs && mount -t proc none proc && mount -t sysfs none sys && mount -t devtmpfs none dev")19 cmd.Run()20 },21 },22 {23 Action: func(c *cli.Context) error {24 fmt.Println("stop a container")25 cmd := exec.Command("sh", "-c", "cd rootfs && umount proc sys dev")26 cmd.Run()27 },28 },29 {30 Action: func(c *cli.Context) error {31 fmt.Println("delete a container")32 cmd := exec.Command("sh", "-c", "rm -rf rootfs workdir")33 cmd.Run()34 },35 },36 }37 app.Run(os.Args)38}

Full Screen

Full Screen

initFromConfigFile

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, playground")4 run.initFromConfigFile()5}6import (7func main() {8 fmt.Println("Hello, playground")9 run.initFromConfigFile()10}11import (12func main() {13 fmt.Println("Hello, playground")14 run.initFromConfigFile()15}16import (17func main() {18 fmt.Println("Hello, playground")19 run.initFromConfigFile()20}21import (22func main() {23 fmt.Println("Hello, playground")24 run.initFromConfigFile()25}26import (27func main() {28 fmt.Println("Hello, playground")29 run.initFromConfigFile()30}31import (32func main() {33 fmt.Println("Hello, playground")34 run.initFromConfigFile()35}36import (37func main() {38 fmt.Println("Hello, playground")39 run.initFromConfigFile()40}41import (42func main() {43 fmt.Println("Hello, playground")44 run.initFromConfigFile()45}

Full Screen

Full Screen

initFromConfigFile

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 flag.Parse()4 err = run.InitFromConfigFile("/home/sagar/Downloads/shelter-master/example/shelter.conf")5 if err != nil {6 fmt.Println(err)7 }8 err = log.Init(run.Config().Log)9 if err != nil {10 fmt.Println(err)11 }12 err = database.Init(run.Config().Database)13 if err != nil {14 fmt.Println(err)15 }16 err = transaction.Init(run.Config().Transaction)17 if err != nil {18 fmt.Println(err)19 }20 err = storage.Init(run.Config().ACME.Storage)21 if err != nil {22 fmt.Println(err)

Full Screen

Full Screen

initFromConfigFile

Using AI Code Generation

copy

Full Screen

1import (2var (3 configFile = flag.String("config", "config.json", "config file")4func main() {5 flag.Parse()6 vm := otto.New()7 run, err := vm.Object("new Run()")8 if err != nil {9 log.Fatalf("Error creating new Run instance: %s", err)10 }11 _, err = run.Call("initFromConfigFile", nil, *configFile)12 if err != nil {13 log.Fatalf("Error calling initFromConfigFile: %s", err)14 }15 _, err = run.Call("run", nil)16 if err != nil {17 log.Fatalf("Error calling run: %s", err)18 }19 sig := make(chan os.Signal, 1)20 signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)21}22import (23var (24 configFile = flag.String("config", "config.json", "config file")25func main() {26 flag.Parse()27 vm := otto.New()28 run, err := vm.Object("new Run()")29 if err != nil {30 log.Fatalf("Error creating new Run instance: %s", err)31 }32 config, err := os.Open(*configFile)33 if err != nil {34 log.Fatalf("Error opening config file: %s", err)35 }36 buf := make([]byte, 1024)37 for {38 n, err := config.Read(buf)39 if err != nil {40 log.Fatalf("Error reading config file: %s", err)41 }42 if n == 0 {43 }44 configString += string(buf

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful