예제 #1
0
def switch_toggle_loop():
    """Toggle the switch on all devices in the directory"""

    global switch_state

    if Registry.size() > 0 and sendSwitchTimer.check():
        print("transmit")
        radio.transmitter()

        for sensorid in Registry.get_sensorids():
            # Only try to toggle the switch for devices that actually have a switch
            header = Registry.get_info(sensorid)["header"]
            mfrid = header["mfrid"]
            productid = header["productid"]

            if Devices.hasSwitch(mfrid, productid):
                request = OpenThings.alterMessage(Messages.SWITCH,
                                                  header_sensorid=sensorid,
                                                  recs_0_value=switch_state)
                p = OpenThings.encode(request)
                print("Sending switch message to %s %s" %
                      (hex(productid), hex(sensorid)))
                # Transmit multiple times, hope one of them gets through
                radio.transmit(p, inner_times=2)

        radio.receiver()
        switch_state = (switch_state + 1) % 2  # toggle
예제 #2
0
def monitor_loop():
    """Capture any incoming messages and log to CSV file"""

    radio.receiver()

    while True:
        # See if there is a payload, and if there is, process it
        if radio.is_receive_waiting():
            trace("receiving payload")
            payload = radio.receive()
            try:
                decoded = OpenThings.decode(payload)
                now = time.time()
            except OpenThings.OpenThingsException as e:
                warning("Can't decode payload:" + str(e))
                continue
                      
            OpenThings.showMessage(decoded, timestamp=now)
            # Any device that reports will be added to the non-persistent directory
            Registry.update(decoded)
            ##trace(decoded)
            Logger.logMessage(decoded)

            # Process any JOIN messages by sending back a JOIN-ACK to turn the LED off
            if len(decoded["recs"]) == 0:
                # handle messages with zero recs in them silently
                print("Empty record:%s" % decoded)
            else:
                # assume only 1 rec in a join, for now
                if decoded["recs"][0]["paramid"] == OpenThings.PARAM_JOIN:
                    mfrid     = OpenThings.getFromMessage(decoded, "header_mfrid")
                    productid = OpenThings.getFromMessage(decoded, "header_productid")
                    sensorid  = OpenThings.getFromMessage(decoded, "header_sensorid")
                    Messages.send_join_ack(radio, mfrid, productid, sensorid)
예제 #3
0
def switch_toggle_loop():
    """Toggle the switch on all devices in the directory"""

    global switch_state

    if Registry.size() > 0 and sendSwitchTimer.check():
        print("transmit")
        radio.transmitter()

        for sensorid in Registry.get_sensorids():
            # Only try to toggle the switch for devices that actually have a switch
            header = Registry.get_info(sensorid)["header"]
            mfrid = header["mfrid"]
            productid = header["productid"]

            if Devices.hasSwitch(mfrid, productid):
                request = OpenThings.alterMessage(Messages.SWITCH,
                    header_sensorid=sensorid,
                    recs_0_value=switch_state)
                p = OpenThings.encode(request)
                print("Sending switch message to %s %s" % (hex(productid), hex(sensorid)))
                # Transmit multiple times, hope one of them gets through
                radio.transmit(p, inner_times=2)

        radio.receiver()
        switch_state = (switch_state+1) % 2 # toggle
예제 #4
0
    def send_data(self, switch_state):
        '''Send data to switch'''

        request = OpenHEMS.alterMessage(self.msg_switch,
                                        recs_0_value=switch_state)
        p = OpenHEMS.encode(request)
        radio.transmitter()
        radio.transmit(p)
        radio.receiver()
예제 #5
0
    def send_data(self, switch_state):

        '''Send data to switch'''

        request = OpenHEMS.alterMessage(self.msg_switch, recs_0_value=switch_state)
        p = OpenHEMS.encode(request)
        radio.transmitter()
        radio.transmit(p)
        radio.receiver()
예제 #6
0
    def get_data(self, monitor_mode= False, short_msg= True):

        '''Send discovery and monitor messages, and capture any responses.
            monitor_mode    True:   will loop continously
                            False:  will stop script once first succesful data 
                                    packet is received (default)
            short_msg       True:   returns long detailed message
                            False:  returns short message (default)'''

        # Define the schedule of message polling
        radio.receiver()
        decoded            = None
        message_not_received = True

        while message_not_received:
            # See if there is a payload, and if there is, process it
            if radio.isReceiveWaiting():
                self.logger.info("receiving payload")
                payload = radio.receive()

                if monitor_mode == False:
                    message_not_received = False

                try:
                    decoded = OpenHEMS.decode(payload)
                except OpenHEMS.OpenHEMSException as e:
                    self.logger.error("Can't decode payload:" + str(e))
                    message_not_received = True
                    continue
                          
                self.updateDirectory(decoded)

                if self.msg_join_ack['header']['sensorid'] == 0 or self.msg_switch['header']['sensorid'] == 0:
                    self.msg_join_ack['header']['sensorid'] = decoded["header"]["sensorid"] 
                    self.msg_switch['header']['sensorid']   = decoded["header"]["sensorid"]
                
                #TODO: Should remember report time of each device,
                #and reschedule command messages to avoid their transmit slot
                #making it less likely to miss an incoming message due to
                #the radio being in transmit mode

                # assume only 1 rec in a join, for now
                if len(decoded["recs"])>0 and decoded["recs"][0]["paramid"] == OpenHEMS.PARAM_JOIN:
                    #TODO: write OpenHEMS.getFromMessage("header_mfrid")
                    response = OpenHEMS.alterMessage(self.msg_join_ack,
                        header_mfrid=decoded["header"]["mfrid"],
                        header_productid=decoded["header"]["productid"],
                        header_sensorid=decoded["header"]["sensorid"])
                    p = OpenHEMS.encode(response)
                    radio.transmitter()
                    radio.transmit(p)
                    radio.receiver()

        if short_msg:
            decoded = self.clean(decoded)
            
        return decoded
예제 #7
0
def send_join_ack(mfrid, productid, sensorid):
    # send back a JOIN ACK, so that join light stops flashing
    response = OpenThings.alterMessage(Messages.JOIN_ACK,
        header_mfrid=mfrid,
        header_productid=productid,
        header_sensorid=sensorid)
    p = OpenThings.encode(response)
    radio.transmitter()
    radio.transmit(p)
    radio.receiver()
예제 #8
0
def monitor_loop():
    radio.receiver()

    while True:
        if radio.isReceiveWaiting():
            payload = radio.receive()
            try:
                decoded = OpenThings.decode(payload)
            except OpenThings.OpenThingsException as e:
                continue

            updateDirectory(decoded)
            tidyDirectory()
            dumpDirectory()

            # Process any JOIN messages by sending back a JOIN-ACK to turn the LED off
            if len(decoded["recs"]) != 0:
                if decoded["recs"][0]["paramid"] == OpenThings.PARAM_JOIN:
                    header    = decoded["header"]
                    mfrid     = header["mfrid"]
                    productid = header["productid"]
                    sensorid  = header["sensorid"]
                    send_join_ack(mfrid, productid, sensorid)
예제 #9
0
def monitor():
    """Send discovery and monitor messages, and capture any responses"""

    # Define the schedule of message polling
    sendSwitchTimer = Timer(60, 1)  # every n seconds offset by initial 1
    switch_state = 0  # OFF
    radio.receiver()
    decoded = None

    while True:
        # See if there is a payload, and if there is, process it
        if radio.isReceiveWaiting():
            trace("receiving payload")
            payload = radio.receive()
            try:
                decoded = OpenHEMS.decode(payload)
            except OpenHEMS.OpenHEMSException as e:
                print("Can't decode payload:" + str(e))
                continue

            OpenHEMS.showMessage(decoded)
            updateDirectory(decoded)
            logMessage(decoded)

            #TODO: Should remember report time of each device,
            #and reschedule command messages to avoid their transmit slot
            #making it less likely to miss an incoming message due to
            #the radio being in transmit mode

            # assume only 1 rec in a join, for now
            if len(decoded["recs"]) > 0 and decoded["recs"][0][
                    "paramid"] == OpenHEMS.PARAM_JOIN:
                #TODO: write OpenHEMS.getFromMessage("header_mfrid")
                response = OpenHEMS.alterMessage(
                    MESSAGE_JOIN_ACK,
                    header_mfrid=decoded["header"]["mfrid"],
                    header_productid=decoded["header"]["productid"],
                    header_sensorid=decoded["header"]["sensorid"])
                p = OpenHEMS.encode(response)
                radio.transmitter()
                radio.transmit(p)
                radio.receiver()

        if sendSwitchTimer.check(
        ) and decoded != None and decoded["header"]["productid"] in [
                Devices.PRODUCTID_C1_MONITOR,
                Devices.PRODUCTID_R1_MONITOR_AND_CONTROL
        ]:
            request = OpenHEMS.alterMessage(
                MESSAGE_SWITCH,
                header_sensorid=decoded["header"]["sensorid"],
                recs_0_value=switch_state)
            p = OpenHEMS.encode(request)
            radio.transmitter()
            radio.transmit(p)
            radio.receiver()
            switch_state = (switch_state + 1) % 2  # toggle
예제 #10
0
def monitor_loop():
    """Capture any incoming messages and log to CSV file"""

    radio.receiver()

    while True:
        # See if there is a payload, and if there is, process it
        if radio.is_receive_waiting():
            trace("receiving payload")
            payload = radio.receive()
            try:
                decoded = OpenThings.decode(payload)
                now = time.time()
            except OpenThings.OpenThingsException as e:
                warning("Can't decode payload:" + str(e))
                continue

            OpenThings.showMessage(decoded, timestamp=now)
            # Any device that reports will be added to the non-persistent directory
            Registry.update(decoded)
            ##trace(decoded)
            Logger.logMessage(decoded)

            # Process any JOIN messages by sending back a JOIN-ACK to turn the LED off
            if len(decoded["recs"]) == 0:
                # handle messages with zero recs in them silently
                print("Empty record:%s" % decoded)
            else:
                # assume only 1 rec in a join, for now
                if decoded["recs"][0]["paramid"] == OpenThings.PARAM_JOIN:
                    mfrid = OpenThings.getFromMessage(decoded, "header_mfrid")
                    productid = OpenThings.getFromMessage(
                        decoded, "header_productid")
                    sensorid = OpenThings.getFromMessage(
                        decoded, "header_sensorid")
                    Messages.send_join_ack(radio, mfrid, productid, sensorid)
예제 #11
0
def monitor():
    """Send discovery and monitor messages, and capture any responses"""

    # Define the schedule of message polling
    sendSwitchTimer    = Timer(5, 1)   # every n seconds offset by initial 1
    switch_state       = 0             # OFF
    radio.receiver()
    decoded            = None

    while True:
        # See if there is a payload, and if there is, process it
        if radio.isReceiveWaiting():
            #trace("receiving payload")
            payload = radio.receive()
            try:
                decoded = OpenHEMS.decode(payload)
            except OpenHEMS.OpenHEMSException as e:
                warning("Can't decode payload:" + str(e))
                continue
                      
            OpenHEMS.showMessage(decoded)
            updateDirectory(decoded)
            logMessage(decoded)
            
            #TODO: Should remember report time of each device,
            #and reschedule command messages to avoid their transmit slot
            #making it less likely to miss an incoming message due to
            #the radio being in transmit mode

            # handle messages with zero recs in them silently
            #trace(decoded)
            if len(decoded["recs"]) == 0:
                print("Empty record:%s" % decoded)
            else:
                # assume only 1 rec in a join, for now
                if decoded["recs"][0]["paramid"] == OpenHEMS.PARAM_JOIN:
                    #TODO: write OpenHEMS.getFromMessage("header_mfrid")
                    # send back a JOIN ACK, so that join light stops flashing
                    response = OpenHEMS.alterMessage(JOIN_ACK_MESSAGE,
                        header_mfrid=decoded["header"]["mfrid"],
                        header_productid=decoded["header"]["productid"],
                        header_sensorid=decoded["header"]["sensorid"])
                    p = OpenHEMS.encode(response)
                    radio.transmitter()
                    radio.transmit(p)
                    radio.receiver()

        if sendSwitchTimer.check() and decoded != None:
            request = OpenHEMS.alterMessage(SWITCH_MESSAGE,
                header_sensorid=decoded["header"]["sensorid"],
                recs_0_value=switch_state)
            p = OpenHEMS.encode(request)
            radio.transmitter()
            radio.transmit(p)
            radio.receiver()
            switch_state = (switch_state+1) % 2 # toggle
예제 #12
0
파일: monitor.py 프로젝트: sjhx/pyenergenie
def monitor():
    """Send discovery and monitor messages, and capture any responses"""

    # Define the schedule of message polling
    sendSwitchTimer    = Timer(60, 1)   # every n seconds offset by initial 1
    switch_state       = 0             # OFF
    radio.receiver()
    decoded            = None

    while True:
        # See if there is a payload, and if there is, process it
        if radio.isReceiveWaiting():
            trace("receiving payload")
            payload = radio.receive()
            try:
                decoded = OpenHEMS.decode(payload)
            except OpenHEMS.OpenHEMSException as e:
                print("Can't decode payload:" + str(e))
                continue
                      
            OpenHEMS.showMessage(decoded)
            updateDirectory(decoded)
            logMessage(decoded)
            
            #TODO: Should remember report time of each device,
            #and reschedule command messages to avoid their transmit slot
            #making it less likely to miss an incoming message due to
            #the radio being in transmit mode

            # assume only 1 rec in a join, for now
            if len(decoded["recs"])>0 and decoded["recs"][0]["paramid"] == OpenHEMS.PARAM_JOIN:
                #TODO: write OpenHEMS.getFromMessage("header_mfrid")
                response = OpenHEMS.alterMessage(MESSAGE_JOIN_ACK,
                    header_mfrid=decoded["header"]["mfrid"],
                    header_productid=decoded["header"]["productid"],
                    header_sensorid=decoded["header"]["sensorid"])
                p = OpenHEMS.encode(response)
                radio.transmitter()
                radio.transmit(p)
                radio.receiver()

        if sendSwitchTimer.check() and decoded != None and decoded["header"]["productid"] in [Devices.PRODUCTID_C1_MONITOR, Devices.PRODUCTID_R1_MONITOR_AND_CONTROL]:
            request = OpenHEMS.alterMessage(MESSAGE_SWITCH,
                header_sensorid=decoded["header"]["sensorid"],
                recs_0_value=switch_state)
            p = OpenHEMS.encode(request)
            radio.transmitter()
            radio.transmit(p)
            radio.receiver()
            switch_state = (switch_state+1) % 2 # toggle
예제 #13
0
    def get_data(self, monitor_mode=False, short_msg=True):
        '''Send discovery and monitor messages, and capture any responses.
            monitor_mode    True:   will loop continously
                            False:  will stop script once first succesful data 
                                    packet is received (default)
            short_msg       True:   returns long detailed message
                            False:  returns short message (default)'''

        # Define the schedule of message polling
        radio.receiver()
        decoded = None
        message_not_received = True
        attempt_count = 2

        while message_not_received:
            # See if there is a payload, and if there is, process it
            if radio.isReceiveWaiting():
                self.logger.info("receiving payload")
                payload = radio.receive()

                if monitor_mode == False:
                    message_not_received = False

                try:
                    decoded = OpenHEMS.decode(payload)
                except OpenHEMS.OpenHEMSException as e:
                    self.logger.error(
                        "Attempt: {attempt} - Can't decode payload: {msg}".
                        format(attempt=attempt_count, msg=str(e)))
                    if receive_attempt > 0:
                        message_not_received = True
                        attempt_count = attempt_count - 1
                    continue

                self.updateDirectory(decoded)

                if self.msg_join_ack['header'][
                        'sensorid'] == 0 or self.msg_switch['header'][
                            'sensorid'] == 0:
                    self.msg_join_ack['header']['sensorid'] = decoded[
                        "header"]["sensorid"]
                    self.msg_switch['header']['sensorid'] = decoded["header"][
                        "sensorid"]

                #TODO: Should remember report time of each device,
                #and reschedule command messages to avoid their transmit slot
                #making it less likely to miss an incoming message due to
                #the radio being in transmit mode

                # assume only 1 rec in a join, for now
                if len(decoded["recs"]) > 0 and decoded["recs"][0][
                        "paramid"] == OpenHEMS.PARAM_JOIN:
                    #TODO: write OpenHEMS.getFromMessage("header_mfrid")
                    response = OpenHEMS.alterMessage(
                        self.msg_join_ack,
                        header_mfrid=decoded["header"]["mfrid"],
                        header_productid=decoded["header"]["productid"],
                        header_sensorid=decoded["header"]["sensorid"])
                    p = OpenHEMS.encode(response)
                    radio.transmitter()
                    radio.transmit(p)
                    radio.receiver()

        if short_msg:
            decoded = self.clean(decoded)

        return decoded
예제 #14
0

if __name__ == "__main__":

    trace("starting switch tester")
    radio.init()
    OpenThings.init(Devices.CRYPT_PID)

    # Seed the registry with a known device, to simplify tx-only testing
    SENSOR_ID = 0x68B  # captured from a real device
    device_header = OpenThings.alterMessage(
        Messages.REGISTERED_SENSOR,
        header_mfrid=Devices.MFRID,
        header_productid=Devices.PRODUCTID_MIHO005,  # adaptor plus
        header_sensorid=SENSOR_ID)
    Registry.update(device_header)

    sendSwitchTimer = Timer(TX_RATE, 1)  # every n seconds offset by initial 1
    switch_state = 0  # OFF
    radio.receiver()

    try:
        while True:
            switch_sniff_loop()
            switch_toggle_loop()

    finally:
        radio.finished()

# END
예제 #15
0
        

if __name__ == "__main__":
    
    trace("starting switch tester")
    radio.init()
    OpenThings.init(Devices.CRYPT_PID)

    # Seed the registry with a known device, to simplify tx-only testing
    SENSOR_ID = 0x68B # captured from a real device
    device_header = OpenThings.alterMessage(Messages.REGISTERED_SENSOR,
        header_mfrid     = Devices.MFRID,
        header_productid = Devices.PRODUCTID_MIHO005, # adaptor plus
        header_sensorid  = SENSOR_ID)
    Registry.update(device_header)


    sendSwitchTimer    = Timer(TX_RATE, 1)   # every n seconds offset by initial 1
    switch_state       = 0 # OFF
    radio.receiver()

    try:
        while True:
            switch_sniff_loop()
            switch_toggle_loop()

    finally:
        radio.finished()

# END