func readChannels(ch fsm.Channels) { buttonChan := getButtons() for { select { case dir := <-ch.MotorDir: driver.Elev_set_motor_direction(dir) case doorLight := <-ch.DoorLight: driver.Elev_set_door_open_lamp(doorLight) case floor := <-ch.NewFloor: driver.Elev_set_floor_indicator(floor) case buttonPressed := <-buttonChan: switch buttonPressed.Button { case def.BUTTON_COMMAND: queue.SetLocalOrder(buttonPressed) case def.BUTTON_DOWN, def.BUTTON_UP: cost.ChooseElevator(onlineLifts, buttonPressed, true) } //Incoming messages case tcpMessage := <-incomingTcpMsg: switch tcpMessage.Type { case def.ORDER: queue.SetLocalOrder(tcpMessage.Order) case def.UPDATEREMOTELIGHT: def.SyncLight <- tcpMessage.Order ch.OrderTimerReset <- true } case message := <-incomingMsg: handleMsg(ch, message) //Outgoing messages case button := <-def.SyncRemoteLights: for i := range onlineLifts { if i == def.LocalElevator.Addr { def.SyncLight <- button } else { go network.TcpConnect(i, def.TcpPort, def.TcpMessage{Type: def.UPDATEREMOTELIGHT, Order: button}) } } //Handles if motor stops working case <-ch.OrderTimerTimeout: for f := 0; f < def.N_FLOORS; f++ { for b := 0; b < def.BUTTON_COMMAND; b++ { if def.LocalElevator.Orders[f][b] { cost.ChooseElevator(onlineLifts, def.ButtonPress{b, f, true, def.LocalElevator.Addr}, false) } } } } } }
func ChooseElevator(onlineLifts map[string]def.Elevator, order def.ButtonPress, includeSelf bool) { bestLift := "0" bestCost := 1000 for i := range onlineLifts { if (i == def.LocalElevator.Addr && includeSelf) || i != def.LocalElevator.Addr { thisCost := calculateCost(onlineLifts[i], order.Floor, order.Button) if thisCost < bestCost { bestCost = thisCost bestLift = i } } } if bestLift != "0" { if bestLift == def.LocalElevator.Addr { queue.SetLocalOrder(order) } else { go network.TcpConnect(bestLift, def.TcpPort, def.TcpMessage{Type: def.ORDER, Order: order}) } } }