/*
 * switch_hal.cpp
 *
 *  Created on: 13 нояб. 2018 г.
   Copyright 2018 alexrayne <alexraynepe196@gmail.com>

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */


#include "switch_hal.hpp"

SwitchLine_Device::SwitchLine_Device(SwitchLine_Device::dev_name name)
:HAL_Device(name)
, pins_amount(0)
, selection(-1)
{
}

//virtual
int SwitchLine_Device::init(){
    for (unsigned l = 0; l < pins_amount; l++)
        pin_set(l, selOFF);
    return select(selNONE);
}

//virtual
int SwitchLine_Device::select(unsigned state){
    if (state > pins_amount)
        return DEV_NOT_IMPLEMENTED;
    int ok = DEV_OK;
    if ((selection > 0) && (selection <= pins_amount)){
        ok = pin_set(selection-1, selOFF);
        selection = selNONE;
    }
    if (state > 0) {
        ok = pin_set(state-1, selON);
        if (ok == DEV_OK)
            selection = state;
    }
    return ok;
}

// \return true if state is selected in switch
bool SwitchLine_Device::is_selected(unsigned state) const{
    if (state > pins_amount)
        return false;
    if (state <= selNONE)
        return (selection > 0);
    return ( pin_state(state-1) == selON);
}

//virtual
int SwitchLine_Device::selected() const{
    return selection;
}

