Advertisement
Guest User

Untitled

a guest
Oct 20th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.79 KB | None | 0 0
  1. import sys
  2. import time
  3. import json
  4. import codecs
  5. import argparse
  6. import numpy as np
  7. import pickle as pkl
  8. import paho.mqtt.client as mqtt
  9.  
  10. def on_message(client, userdata, msg):
  11.     m_decode = str(msg.payload.decode("utf-8","ignore"))
  12.     print(m_decode)
  13.     print("data Received type:",type(m_decode))
  14.     print("data Received",m_decode)
  15.     #Processing message payload
  16.     #Converting received data from json to object
  17.     tmp1 = json.loads(m_decode)
  18.     data_in = np.array(tmp1[0])
  19.     ncols = tmp1[1]
  20.  
  21.     #Reshaping 1-D array to 2-D array
  22.     converted_arr = np.reshape(data_in, (-1, ncols))
  23.     print("\n Array after de-serialization")
  24.     print(converted_arr)
  25.  
  26. def array_to_cloud():
  27.     i = input("Enter row dimensions:")
  28.     i = int(i)
  29.     j = input("Enter column dimensions:")
  30.     j = int(j)
  31.     print("Dimensions:",i,j)
  32.     #Creating random values to fill the np array
  33.     a = np.random.randint(low=1,high=11,size=(i,j))
  34.     print(a)
  35.     #Duplicating array
  36.     b = a
  37.     #Concatenating matrix rows
  38.     print("\nConcatenating matrix rows")
  39.     a = a.ravel()
  40.     print(a)
  41.     #Converting array to list
  42.     new_a = a.tolist()
  43.     #print(new_a)
  44.     #Creating a list consisting of the 1D array and its column zdimensions(j)
  45.     tmp = []
  46.     tmp = [new_a,j]
  47.     data_out = json.dumps(tmp)
  48.     print("data_out type:",type(data_out))
  49.     return data_out
  50.  
  51.  
  52. topic="test/json_test"
  53. client=mqtt.Client("pythontest1")
  54. client.on_message=on_message
  55. print("\n\n MQTT:\n\n")
  56. print("Connecting to broker ","localhost")
  57. client.connect("localhost")
  58. client.loop_start()
  59.  
  60. client.subscribe(topic)
  61. time.sleep(3)
  62. print("sending data")
  63.  
  64. data_out = array_to_cloud()
  65. client.publish(topic,data_out)
  66.  
  67. time.sleep(2)
  68. client.loop_stop()
  69. client.disconnect()
  70. print("Connection closed!")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement