Exemplo n.º 1
0
def transmit_mqtt(form_obj):
    """
    This function is not a view.
    This function transmits a validated message.
    Janus, March 2020
    """

    # Print to console for debug
    print(form_obj)

    # Create a message to send
    topic = form_obj['topic']
    # Payload
    m = protocol.Message()
    m.new()
    m.sentBy = form_obj['sender']
    m.msgType = form_obj['msg_type']
    m.statusCode = form_obj['status_code']

    # try-except on the json conversions
    # convert json -> python
    try:
        m.commandList = json.loads(form_obj['command_list_str'])
    except:
        print("Error converting commandlist -> insert empty")

    try:
        m.dataObj = json.loads(form_obj['data_obj_str'])
    except:
        print("Error converting dataObj -> insert empty")

    try:
        m.parameterObj = json.loads(form_obj['parameter_obj_str'])
    except:
        print("Error converting parameterObj -> insert empty")

    # Done inserting data
    m.pack()
    send_me = protocol.ProtocolSchema.write_jsonstr(m.payload)

    # debug output to console
    print(send_me)

    # Send it

    # The donothing callback function
    def donothing(client, userdata, message):
        pass

    # Create client
    publisher = MqttClient("DemoModuleMessageSender", donothing)

    # Send and disconnect
    rc = publisher.publish(topic, send_me)
    publisher.disconnect()

    return rc
        def on_message_callback(client, userdata, message):

            #Create a new message object
            m = protocol.Message()

            # Convert the incoming JSON message to Python vars
            msg = message.payload.decode("utf-8")
            obj = protocol.ProtocolSchema.read_jsonstr(msg)

            # Do some validation here
            # Evaluate if the Python object conforms to the protocol
            schema_validation_result = protocol.ProtocolSchema.validating(
                obj, m.protocol_schema)

            # Consider implementing a break if the validation fails.

            # Insert into struct-like variables in the m-object.
            m.unpack(**obj)

            # Store any received statuscodes
            # 6xx -> Power Codes
            # 1xx-5xx -> Status Codes
            if m.msgType == "status":
                # Get object in the db
                s = Status.objects.all()[0]

                if int(m.statusCode) >= 600:
                    s.latest_power_code = m.statusCode
                else:
                    s.latest_status_code = m.statusCode

                # Update the object
                s.save()

            if m.msgType == "data":
                # Create and store a new result in the db
                r = Result()

                # Needs to be decided:
                # - How to transport the nodelete tag through a roundtrip?
                # - How to transport the requested_by tag through a roundtrip?
                # - Is it the right choice to store the embedded file as binary? Do we need it?

                # Set relevant values from message
                r.command_list = m.commandList
                r.parameter_obj = m.parameterObj
                r.data_obj = m.dataObj
                r.embedded_file_format = m.embeddedFileFormat
                r.embedded_file = bytearray(m.embeddedFile, "utf8")

                # Create the object in the db
                r.save()
Exemplo n.º 3
0
        def on_message_callback(client, userdata, message):

            # Create a new message object
            m = protocol.Message()

            # Convert the incoming JSON message to Python vars
            msg = message.payload.decode("utf-8")
            obj = protocol.ProtocolSchema.read_jsonstr(msg)

            # Do some validation here
            # Evaluate if the Python object conforms to the protocol
            schema_validation_result = protocol.ProtocolSchema.validating(
                obj, m.protocol_schema)

            # If validation fails it will give a boolean fail in the database, and skip the unpacking process
            if schema_validation_result == True:

                # Insert into struct-like variables in the m-object.
                m.unpack(**obj)
                package = obj

                # Store any received statuscodes
                # 6xx -> Power Codes
                # 1xx-5xx -> Status Codes
                if m.msgType == "status":
                    # Get object in the db
                    s = Status()
                    s.ID = 0

                    if int(m.statusCode) >= 600:
                        s.latest_power_code = m.statusCode
                    else:
                        s.latest_status_code = m.statusCode

                    # Update the object
                    s.save()

                # For inbound data
                if m.msgType == "data":

                    # Create and store a JSON package in the db
                    ITP = Inbound_teststand_package()

                    # TimeStamp and nodelete copied from temporary model
                    temp = ND_TS.objects.all()[0]
                    ITP.Timestamp = temp.TimeStamp
                    ITP.NODELETE = temp.NoDelete

                    # Store values from inbound validated JSON
                    ITP.Sent_by = package["sentBy"]
                    ITP.command_list = package["commandList"]
                    ITP.Validation_failed = 0
                    ITP.save()

                    # Parameter's table
                    for p_name, p_val in package["parameterObj"].items():
                        print(p_name, p_val)
                        TSP = Test_stand_parameters()
                        TSP.Parameter_name = p_name
                        TSP.Parameter_value = p_val
                        TSP.Inbound_teststand_package = ITP
                        TSP.save()

                    # Data table
                    for data_name, data_points in package["dataObj"].items():
                        print(data_name, data_points)
                        TSD = Test_stand_data()
                        TSD.Data_name = data_name
                        TSD.Data_points = data_points
                        TSD.Inbound_teststand_package = ITP
                        TSD.save()

            else:
                package = obj

                # Create and store a JSON package in the db
                ITP = Inbound_teststand_package()

                # TimeStamp
                Timestamp = datetime.now()

                if "sentBy" in package:
                    ITP.Sent_by = package["sentBy"]
                else:
                    ITP.Sent_by = "Failed validation"

                ITP.Timestamp = Timestamp.strftime("%x-%I:%M:%S")
                ITP.Validation_failed = 1

                ITP.save()