python上报IP

通过http://wy.mikuq.com/api/ip/获取本地IP上报给MikuQ

import paho.mqtt.client as mqtt
import threading
import time
import urllib2

url = "http://wy.mikuq.com/api/ip/"

client = mqtt.Client()
client.connect("mikuq", 1883, 50)

def heart_beat():
    mydt = time.strftime('%Y-%m-%d %H:%M:%S')

    ip = "0.0.0.0"

    try:
      req = urllib2.Request(url)
      res_data = urllib2.urlopen(req)
      ip = res_data.read()
    except:
      print "error"

    print mydt, ip

    global client
    client.publish("mqtt/timer", "{\"time\":\"" + mydt + "\",\"ip\":\"" + ip + "\"}")
    threading.Timer(10, heart_beat).start()

heart_beat()
client.loop_forever()

订阅并记录文件

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import paho.mqtt.client as mqtt
import os.path as Path
import threading
import time
import shutil

full_fn = ''
fn=''

def on_connect(client, userdata, flags, rc):
  print 'on_connect'
  client.subscribe("mqtt/#")

def on_message(client, userdata, msg):
  global full_fn
  print msg.topic.decode("utf-8")
  print msg.payload.decode("utf-8")
  dt = time.strftime('%Y-%m-%d %H:%M:%S')
  fo = open(full_fn, "a+")
  fo.write(dt + '|' + msg.topic.decode("utf-8") + '|' + msg.payload.decode("utf-8") + '\n')
  fo.close()

def heart_beat():
  global full_fn
  global fn
  nfn = time.strftime('%Y%m%d') + '.dat'
  if full_fn!='':
    if fn != nfn:
      print fn
      if Path.exists(full_fn):
        shutil.move(full_fn, '/home/fa/data/' + fn)
      fn = nfn
      full_fn = '/ramdisk/' + fn
  else:
    fn = nfn
    full_fn = '/ramdisk/' + fn

  threading.Timer(1, heart_beat).start()

heart_beat()
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("mikuq", 1883, 50)
client.loop_forever()

标签: none

添加新评论