#!/usr/bin/python import threading import time from device_base import deviceBase import requests try: import json except: import simplejson as json channels = {} min_upload_time = 120 addr = 'http://192.168.1.30:3000' def setupChannels(): tagJSObj = json.loads(requests.get(addr + "/tag").text) for t in tagJSObj: channel_name = t['name'].replace(" ", "").lower() channels[channel_name] = { 'tagID': t['id'], 'last_value': -999, 'data_type': t['data_type']['plc_type'], 'last_time_uploaded': 0, 'change_amount': t['change_threshold'], 'min_time_between_uploads': min_upload_time } class start(threading.Thread, deviceBase): def updateGPS(self): gps = self.mcu.gps print("GPS found me at {0}".format(gps)) self.sendtodb("gps", gps, 0) def __init__(self, name=None, number=None, mac=None, Q=None, mcu=None, companyId=None, offset=None, mqtt=None, Nodes=None): threading.Thread.__init__(self) deviceBase.__init__(self, name=name, number=number, mac=mac, Q=Q, mcu=mcu, companyId=companyId, offset=offset, mqtt=mqtt, Nodes=Nodes) self.daemon = True self.version = "3" self.device_address = addr self.finished = threading.Event() threading.Thread.start(self) self.sendtodbJSON("device_address", self.device_address, 0) setupChannels() self.updateGPS() def register(self): channels["status"]["last_value"] = "" def run(self): self.runLoopStatus = "" last_OK_state = 0 while True: if len(channels) > 0: try: latest_vals = json.loads(requests.get(self.device_address + "/tag_val/latest").text) for tag in latest_vals: runLoopStatus = tag['name'] ch_name = tag['name'].replace(" ", "").lower() if ch_name in channels: ch = channels[ch_name] nowVal = tag['val'] if (abs(ch['last_value'] - nowVal) > ch['change_amount']) or ((time.time() - ch['last_time_uploaded']) > ch['min_time_between_uploads']): self.sendtodbJSON(ch_name, nowVal, 0) ch['last_time_uploaded'] = time.time() ch['last_value'] = nowVal runLoopStatus = "Complete" OK_state = 1 if not OK_state == last_OK_state: self.sendtodbJSON("driverok", OK_state, 0) last_OK_state = OK_state time.sleep(3) except Exception, e: OK_state = 0 if not OK_state == last_OK_state: self.sendtodbJSON("driverok", OK_state, 0) last_OK_state = OK_state sleep_timer = 20 print "Error during {0} of run loop: {1}\nWill try again in {2} seconds...".format(runLoopStatus, e, sleep_timer) time.sleep(sleep_timer) else: setupChannels() time.sleep(30) def tagserver_sync(self, name, value): self.sendtodb("connected", "true", 0) return True def tagserver_address(self, name, value): self.device_address = value return True def tagserver_gpsUpdate(self, name, value): global updateGPS updateGPS() return True