Пример #1
0
def on_connect(client, userdata, flags, rc):
    """ We have connected to the broker, set up our subscriptions and publications """

    logger.debugf("on_connect BEGIN")
    logger.debugf("ID=%s= U=%s= Flgs=%s= RC=%s=" %
                  (client._client_id, userdata, flags, rc))

    topic = TopicMaker.makeTopicDhcpAllReq()

    dhcpCfgDct = ConfigListOfDict.getInstance().findDhcpConfigDict()

    dhcpCfgDct.setMqSub(Constants.CFG_VALUE_DEFAULT_CONNECT)

    dhcpCfgDct.setMqPub(topic)

    jsonStr = ConfigListOfDict.getInstance().toJsonStr()

    logger.debugf("Publish %s PyLd: %s" % (topic, jsonStr))

    mqtt.publish(topic, payload=jsonStr, qos=0, retain=False)

    mqtt.subscribe(TopicMaker.makeTopicDhcpAllRsp())

    mqtt.subscribe(TopicMaker.makeTopicDhcpReq())

    logger.debugf("on_connect END")

    return
Пример #2
0
def newDhcpTable(message):

    logger.debugf("newDhcpTable BEGIN")

    jstr = message.payload.decode()

    logger.debugf("Msg=%s=", jstr)

    ConfigListOfDict.fromJsonStr(jstr)  #start using the new DHCP table

    ConfigListOfDict.getInstance().updateMyCfgDict(hostName, activeNIF,
                                                   mySysType)

    debugWriteConfigFileUpd(Constants.CFG_FILE_NAME_DEBUG_SLAVE)

    # subscribe to all messages directed to me at my MAc address
    mmacAddr = activeNIF.getMacAddrAsHexStr()

    mqtt.message_callback_add(mmacAddr, on_topic_MacAddressCallback)

    mqtt.subscribe(mmacAddr)

    # subscribe to all messages directed to me at my Title
    # my Title should be the same as my GPS address
    gps = ConfigListOfDict.getInstance().getTitle(mmacAddr, mySysType)

    globalGps.setGps(gps)

    mqtt.message_callback_add(globalGps.getGps(), on_topic_GpsAddressCallback)

    mqtt.subscribe(gps)

    logger.debugf("newDhcpTable END")

    return
Пример #3
0
def on_topicDhcpReq(client, userdata, mqttMessage):

    logger.debugf("on_topic(%s) BEGIN" % onTopic)

    localCfgDict = updateLocalDhcpRecordWithRemoteData(mqttMessage)

    rspTopicMkr = TopicMaker(localCfgDict.getMacAddrSelf())

    rspTopic = rspTopicMkr.makeTopicDhcpRsp()

    #localCfgDict.setMqPub(rspTopic)

    dhcpCfgDct = ConfigListOfDict.getInstance().findDhcpConfigDict()

    dhcpCfgDct.setMqPub(rspTopic)

    jsonStr = ConfigListOfDict.getInstance().toJsonStr()

    logger.debugf("Publish %s" % jsonStr)

    mqtt.publish(rspTopic, payload=jsonStr, qos=0, retain=False)

    logger.debugf("on_topic(%s) END" % onTopic)

    return
def on_connect(client, userdata, flags, rc):
    """ We have connected to the broker, set up our subscriptions and publications """

    logger.debugf("on_connect BEGIN")
    #logger.debugf("ID={}= U={}= Flgs={}= RC={}=".format(client, userdata, flags, rc))
    #logger.debugf("ID={}= U={}= Flgs={}= RC={}=".format(client._client_id, userdata, flags, rc))

    mqtt.subscribe(TopicMaker.makeTopicSubscribeAll())
    mqtt.subscribe(TopicMaker.makeTopicDhcpAllReq())
    mqtt.subscribe(monitorTopicMaker.makeTopicDhcpRsp())

    myMacAddr = activeNIF.getMacAddrAsHexStr()
    cfgDict = ConfigListOfDict.getInstance().findMonitorConfigDict(myMacAddr)
    topic = TopicMaker.makeTopicDhcpReq()
    cfgDict.setMqPub(topic)
    cfgDict.setMqSub(Constants.CFG_VALUE_DEFAULT_CONNECT)
    cfgDict.setMsgLast()

    jstr = cfgDict.toJsonStr()
    ret = mqtt.publish(topic, payload=jstr, qos=0, retain=False)

    logger.debugf("Sending DHCP REQ with Record %s", jstr)
    logger.debugf("Ret::%s", ret)

    logger.debugf("on_connect END")

    return
Пример #5
0
def on_topicAllSignonReq(client, userdata, message):
    """ docstring"""

    on_topic_str = slaveTopicMaker.makeTopicSignonReq()

    logger.debugf("on_topic(%s) BEGIN", on_topic_str)

    logger.debugf("ID=%s= U=%s= Msg=%s=", client, userdata, message)

    jstr = message.payload.decode()
    logger.debugf("msg.topic=%s= payload=%s= qos=%s=", message.topic, jstr,
                  message.qos)

    rmtCfg = ConfigDict.fromJsonStr(jstr)

    rspTopicMaker = TopicMaker(rmtCfg.getMacAddrSelf())

    myCfgDct = ConfigListOfDict.getInstance().findConfigDict(
        activeNIF.getMacAddrAsHexStr(), mySysType)

    jstr = myCfgDct.toJsonStr()

    mqtt.publish(rspTopicMaker.makeTopicSignonRsp(), jstr, qos=0, retain=False)

    logger.debugf("on_topic(%s) END", on_topic_str)

    return
Пример #6
0
def mac():
    macList = []
    macAddresses = ConfigListOfDict.getInstance().findAllSlavesForMaster(
        activeNIF.getMacAddrAsHexStr())
    for i in macAddresses:
        macList.append(i.getMacAddrSelf())
    return render_template("mac.html", macList=macList)
def on_topicDhcpAllReq(client, userdata, message):
    """ docstring"""

    on_topic_str = TopicMaker.makeTopicDhcpAllReq()

    logger.debugf("on_topic(%s) BEGIN", on_topic_str)

    newDhcpTable(message)

    cfgDict = ConfigListOfDict.getInstance().findMonitorConfigDict(
        activeNIF.getMacAddrAsHexStr())

    cfgDict.setMsgLast()

    jstr = cfgDict.toJsonStr()

    ret = mqtt.publish(TopicMaker.makeTopicDhcpAllRsp(),
                       payload=jstr,
                       qos=0,
                       retain=False)

    logger.debugf("Sending updated cfgDct: %s", jstr)

    logger.debugf("Ret::%s", ret)

    logger.debugf("on_topic(%s) END", on_topic_str)

    return
def newDhcpTable(message):

    logger.debugf("newDhcpTable BEGIN")

    jstr = message.payload.decode()

    logger.debugf("Msg=%s=", jstr)

    ConfigListOfDict.fromJsonStr(jstr)  #start using the new DHCP table

    ConfigListOfDict.getInstance().updateMyCfgDict(
        hostName, activeNIF, Constants.CFG_VALUE_SYS_TYPE_MONITOR)

    debugWriteConfigFileUpd(Constants.CFG_FILE_NAME_DEBUG_MONITOR)

    logger.debugf("newDhcpTable END")

    return
Пример #9
0
def updateSlaveConfigDict(message):

    logger.debugf("newSlaveConfigDict BEGIN")

    jstr = message.payload.decode()

    logger.debugf("Msg=%s=" % jstr)

    rmtDct = ConfigDict.fromJsonStr(jstr)

    lclDct = ConfigListOfDict.getInstance().updateCfgDct(rmtDct)

    if not lclDct:
        ConfigListOfDict.getInstance().addConfigDict(rmtDct)
        rmtDct.setMsgLast()

    debugWriteConfigFileUpd(Constants.CFG_FILE_NAME_DEBUG_MASTER)

    logger.debugf("newSlaveConfigDict END")
    return
Пример #10
0
def updateLocalDhcpRecordWithRemoteData(mqttMessage):

    logger.debugf("updateLocalDhcpRecordWithRemoteData BEGIN")

    sstr = mqttMessage.payload.decode()  # convert from binary to string

    remoteDhcpDict = ConfigDict.fromJsonStr(sstr)

    localCfgDict = ConfigListOfDict.getInstance().updateCfgDct(remoteDhcpDict)

    if not localCfgDict:
        ConfigListOfDict.getInstance().appendConfigDict(remoteDhcpDict)
        localCfgDict = remoteDhcpDict

    localCfgDict.setMsgLast()

    debugWriteConfigFileUpd(Constants.CFG_FILE_NAME_DEBUG_DHCP)

    logger.debugf("msgPLd=%s=" % localCfgDict)

    logger.debugf("updateLocalDhcpRecordWithRemoteData END")

    return localCfgDict
Пример #11
0
def makeCollectionOfSlavesForMap():
    logger.debugf('makeCollectionOfSlavesForMap BEGIN')
    lslaves = []  #list of dictionaries
    configSlaves = ConfigListOfDict.getInstance().findAllSlavesForMaster(
        activeNIF.getMacAddrAsHexStr())
    for cfgDict in configSlaves:
        dct = cfgDict.getDict()
        dslave = {}
        dslave[Constants.CFG_KEY_ICON] = dct[Constants.CFG_KEY_ICON]
        dslave[Constants.CFG_KEY_LAT] = dct[Constants.CFG_KEY_LAT]
        dslave[Constants.CFG_KEY_LNG] = dct[Constants.CFG_KEY_LNG]
        dslave[Constants.CFG_KEY_MAC_SELF] = dct[Constants.CFG_KEY_MAC_SELF]
        dslave[Constants.CFG_KEY_TITLE] = dct[Constants.CFG_KEY_TITLE]
        lslaves.append(dslave)
    jstr = json.dumps(lslaves, indent=4, separators=(',', ':'))
    logger.debugf("All matching slaves: %s" % jstr)
    logger.debugf('makeCollectionOfSlavesForMap END')
    return lslaves
Пример #12
0
def makeMessagePayload(ppubTopic, psubTopic):
    """ docstring"""
    logger.debugf("makeMessagePayload BEGIN pub topib %s", ppubTopic)

    myMacAddr = activeNIF.getMacAddrAsHexStr()

    myCfgDct = ConfigListOfDict.getInstance().findConfigDict(
        myMacAddr, mySysType)

    myCfgDct.setMqPub(ppubTopic)

    myCfgDct.setMqSub(psubTopic)

    myCfgDct.setMsgLast()

    jstr = myCfgDct.toJsonStr()

    logger.debugf("makeMessagePayload END")

    return jstr
Пример #13
0
def sendSignOnToSlaves():

    logger.debugf("sendSignOnToSlaves BEGIN")

    myMacAddr = activeNIF.getMacAddrAsHexStr()
    slavesLofD = ConfigListOfDict.getInstance().findAllSlavesForMaster(
        myMacAddr)

    for slvCfg in slavesLofD:
        slvMacAddr = slvCfg.getMacAddrSelf()
        slvTopMkr = TopicMaker(slvMacAddr)
        topic = slvTopMkr.makeTopicSignonReq()
        slvCfg.setMsgLast()
        jstr = slvCfg.toJsonStr()
        ret = mqtt.publish(topic, payload=jstr, qos=0, retain=False)
        logger.debugf("Sending Slave Signon REQ %s" % topic)
        logger.debugf("Ret:%d mid:%d" % ret)

    logger.debugf("sendSignOnToSlaves END")
    return
    def increment_panel_angle(self, angle_to_move,
                              direction):  #direction is a passed method
        secsPerDeg = ConfigListOfDict.getInstance().findConfigDict(
            SolarThread.__macAddr,
            Constants.CFG_VALUE_SYS_TYPE_SLAVE).getTimeToMoveOneDegree()
        print("SolarThread.__stop_increment: ",
              SolarThread.__stop_increment_angle)
        print("angle to move: ", angle_to_move)
        SolarThread.__stop_increment_angle = False
        if angle_to_move + SolarThread.__current_angle > 45:
            print(">45")
            angle_to_move = 45 - SolarThread.__current_angle  # +1 for good luck  find reasonable time to reach max angle
            time_to_move = time.time() + (abs(angle_to_move) * 10) + 20
        elif angle_to_move + SolarThread.__current_angle < -45:
            print("<45")
            angle_to_move = -45 - SolarThread.__current_angle  # +1 for good luck  find reasonable time to reach max angle
            time_to_move = time.time() + (abs(angle_to_move) * 10) + 20
        else:
            print("not either case")
            time_to_move = time.time() + (abs(angle_to_move) * 10)
        print("time to move :", time_to_move - time.time())
        sign = direction()
        while (time.time() <= time_to_move + 1
               and SolarThread.__stop_increment_angle != True):
            print("__stop_increment_angle: ",
                  SolarThread.__stop_increment_angle)
            SolarThread.__current_angle = SolarThread.__current_angle + (
                sign * (1 / (2 * 10)))
            SolarThread.__update_solar_animation()
            if SolarThread.__current_angle > 45:
                SolarThread.__current_angle = 45
                SolarThread.__update_solar_animation()
            elif SolarThread.__current_angle < -45:
                SolarThread.__current_angle = -45
                SolarThread.__update_solar_animation()
            time.sleep(.5)  #constant
            print(SolarThread.__current_angle)

        SolarThread.stop_all()
        SolarThread.__stop_increment_angle = False
Пример #15
0
def on_connect(client, userdata, flags, rc):
    """ We have connected to the broker, set up our subscriptions and publications """

    logger.debugf("on_connect BEGIN")
    #logger.debugf("ID={}= U={}= Flgs={}= RC={}=".format(client, userdata, flags, rc))
    #logger.debugf("ID={}= U={}= Flgs={}= RC={}=".format(client._client_id, userdata, flags, rc))

    mqtt.subscribe('initialize', 2)
    mqtt.subscribe('pushNotification')
    #mqtt.subscribe('altitude')
    mqtt.publish('subscriber', 'connectToPublisher', 2)

    mqtt.subscribe(masterTopicMaker.makeTopicDhcpAllReq())
    mqtt.subscribe(masterTopicMaker.makeTopicDhcpRsp())

    mqtt.subscribe(masterTopicMaker.makeTopicSignonRsp())
    mqtt.subscribe(masterTopicMaker.makeTopicCmdRsp())

    myMacAddr = activeNIF.getMacAddrAsHexStr()
    cfgDict = ConfigListOfDict.getInstance().findMasterConfigDict(myMacAddr)
    topic = masterTopicMaker.makeTopicDhcpReq()
    cfgDict.setMqPub(topic)
    cfgDict.setMqSub(Constants.CFG_VALUE_DEFAULT_CONNECT)
    cfgDict.setMsgLast()

    jstr = cfgDict.toJsonStr()
    ret = mqtt.publish(topic, payload=jstr, qos=0, retain=False)

    logger.debugf("Sending DHCP REQ with Record %s" % jstr)
    logger.debugf("Ret:%d mid:%d" % ret)

    sendSignOnToSlaves()

    logger.debugf("on_connect END")

    return
Пример #16
0
def sendSignonRsp(psubTopic):
    """ master sends signon req
        slave responds with signon rsp
    """
    logger.debugf("sendSignonRsp BEGIN")

    masterMacAddr = ConfigListOfDict.getInstance().getMacAddrOfMasterForSlave(
        activeNIF.getMacAddrAsHexStr())

    masterTopicMaker = TopicMaker(masterMacAddr)

    ppubTopic = masterTopicMaker.makeTopicSignonRsp()

    jstr = makeMessagePayload(ppubTopic, psubTopic)

    logger.debugf("Publishing::topic=%s= msg=%s=", ppubTopic, jstr)

    ret = mqtt.publish(ppubTopic, jstr)

    logger.debugf("Ret::%s", ret)

    logger.debugf("sendSignonRsp END")

    return
 def __get_dictionary(self):
     return ConfigListOfDict.getInstance().findConfigDict(
         self.__macAddr, Constants.CFG_VALUE_SYS_TYPE_SLAVE)
###########################################################################################
###########################################################################################

LOG_FNAME = 'monitor.log'

logger = initSysLog(LOG_FNAME)

activeNIF = ActiveNIF()

hostName = HostName()

monitorTopicMaker = TopicMaker(activeNIF.getMacAddrAsHexStr())

initConfig(Constants.CFG_FILE_PATH, Constants.CFG_FILE_NAME_STARTUP)

ConfigListOfDict.getInstance().updateMonitorDict(hostName, activeNIF)


def debugWriteConfigFileUpd(fname):
    debugWriteConfigFile(Constants.CFG_FILE_PATH, fname + '.upd')
    return


debugWriteConfigFileUpd(Constants.CFG_FILE_NAME_DEBUG_MONITOR)

###########################################################################################
###########################################################################################
###########################################################################################
###########################################################################################

app = Flask(__name__)
    def trackSolar(self):
        logger = SysLog.getLogger()
        myConfigDict = ConfigListOfDict.getInstance().findConfigDict(
            SolarThread.__macAddr, Constants.CFG_VALUE_SYS_TYPE_SLAVE)
        secsPerDeg = myConfigDict.getTimeToMoveOneDegree()
        print(secsPerDeg)
        gpsCoor = myConfigDict.getGpsCoor()
        gps_lat = gpsCoor[GPS_COOR_LAT]
        gps_lng = gpsCoor[GPS_COOR_LNG]
        last_recorded_azimuth = None
        SolarThread.__stop_increment_angle = False
        if SolarThread.__thread != None:
            print("SolarThread.__thread!=None")
            return -1
        else:
            SolarThread.__thread = self
        #if SolarThread.__current_angle == None: Commented out for testing
        #    print("Please call Calibrate First")
        #    super().stop_thread()

        if SolarThread.__manual_stop_time_angle is not None:
            angle_to_move = SolarThread.__compute_change_in_azimuth()

            if SolarThread.__angle_to_move > 0:
                logger.debugs("Solar Thread turn on west relay")
                SolarThread.increment_panel_angle(
                    angle_to_move, SolarThread.__turn_on_west_relay)

            elif SolarThread.__angle_to_move < 0:
                logger.debugs("Solar Thread turn on east relay")
                SolarThread.increment_panel_angle(
                    angle_to_move, SolarThread.__turn_on_east_relay)
        #Panel should be in correct position from code above
        SolarThread.__manual_stop_time_angle = None

        print("This is SolarThread.__current_angle",
              SolarThread.__current_angle)
        if last_recorded_azimuth == None:
            last_recorded_azimuth = get_azimuth(SolarThread.__latitude,
                                                SolarThread.__longitude,
                                                SolarThread.get_time())
        while True:

            logger.debugs("SolarThread")
            if super().get_stop_thread():
                logger.debugs("THREAD STOPPED")
                SolarThread.__thread = None
                break
            current_azimuth = get_azimuth(
                SolarThread.__latitude, SolarThread.__longitude,
                SolarThread.get_time())  #gps_lat, gps_lng, current_time, 0)
            print("current azimuth", current_azimuth)
            new_angle = current_azimuth - 180  # change back to 180!!!!
            if new_angle > -45 and new_angle < 45:  #when we would start moving the panel
                SolarThread.__reset_called = False  # reset...reset for next day
                SolarThread.__max_angle_check = False
                print("This is new angle: ", new_angle)
                print("This is current angle: ", SolarThread.__current_angle)
                difference = new_angle - SolarThread.__current_angle
                print("This is difference: ", difference)
                if difference >= Constants.ST_ANGLE:
                    print("Larger than")
                    self.increment_panel_angle(
                        difference, SolarThread.__turn_on_west_relay)
                elif difference < (-1 * Constants.ST_ANGLE):
                    print("Smaller than")
                    self.increment_panel_angle(
                        difference, SolarThread.__turn_on_east_relay)
                last_recorded_azimuth = current_azimuth
                time.sleep(Constants.ST_TIME_WAIT_SHORT)
            elif 225 < current_azimuth < 280 and SolarThread.__current_angle != 45 and SolarThread.__max_angle_check == False:  #azimuth should be 225 for a 45* angle
                print("notreset")
                difference = 45 - SolarThread.__current_angle + 2
                self.increment_panel_angle(difference,
                                           SolarThread.__turn_on_west_relay)
                SolarThread.__max_angle_check = true
            elif ((0 < current_azimuth and current_azimuth < 90)
                  or current_azimuth >= 280
                  ) and SolarThread.__reset_called == False:
                print("reset")
                difference = -100
                self.increment_panel_angle(difference,
                                           SolarThread.__turn_on_east_relay)
                SolarThread.__reset_called = True
            else:
                time.sleep(Constants.ST_TIME_WAIT_SHORT)
                logger.debugs("new angle %s" % new_angle)
                logger.debugs("current angle %s" % SolarThread.__current_angle)
Пример #20
0
#
#       Change
#               #@GPIO@# """                                <<<< Disable GPIO
#       to
#               #@GPIO@# ###                                <<<< Enable GPIO
#

### #@GPIO@#    Enable/Disable GPIO
import RPi.GPIO as GPIO
##@GPIO@##        Enable/Disable #@GPIO@# ###

###########################################################################################
###########################################################################################
###########################################################################################
###########################################################################################
ConfigListOfDict.getInstance()


def initSysLog(fname):
    """ docstring """
    syslog = SysLog.initialize(
        __name__, fname,
        "%(asctime)s - %(name)s - %(levelname)s - %(message)s", logging.DEBUG)
    syslog = LogAllOn(syslog)
    #syslog = LogAllOff(syslog)
    #syslog = LogF(syslog)
    #syslog = LogS(syslog)
    syslog = SysLog.setLogger(syslog)
    syslog.info("Log Started")
    return syslog
Пример #21
0
def debugWriteConfigFile(pth, fname):
    """ docstring """
    ConfigListOfDict.getInstance().writeConfigFile(pth, fname)
    return
Пример #22
0
LOG_FNAME = 'dhcp.log'

logger = initSysLog(LOG_FNAME)

activeNIF = ActiveNIF()

hostName = HostName()

mySysType = Constants.CFG_VALUE_SYS_TYPE_DHCP

_dhcpTopicMaker = TopicMaker(activeNIF.getMacAddrAsHexStr())

initConfig(Constants.CFG_FILE_PATH, Constants.CFG_FILE_NAME_DHCP)

ConfigListOfDict.getInstance().updateMyCfgDict(
    hostName, activeNIF, Constants.CFG_VALUE_SYS_TYPE_DHCP)


def debugWriteConfigFileUpd(fname):
    debugWriteConfigFile(Constants.CFG_FILE_PATH, fname + '.upd')
    return


debugWriteConfigFileUpd(Constants.CFG_FILE_NAME_DEBUG_DHCP)

###################################################################################
####
###################################################################################

#myMacAddr = hex(uuid.getnode())         # hex returns a string