def main(args): if args.https: conn = http.client.HTTPSConnection("data.jkoolcloud.com", timeout=10) conn.connect() msg = "<access-request><token>" + args.https + "</token></access-request>" headers = {"Content-Type": "text/plain"} conn.request("POST", "", msg, headers) response = conn.getresponse() data = response.read() headers = {"Content-Type":"application/json"} msg = {"operation":"tnt4py", "type":"EVENT", "msg-text":args.msg} msg = json.dumps(msg) conn.request("POST", "", msg, headers) response = conn.getresponse() data = response.read() print(response.status, response.reason) conn.close() if args.mqtt: topic = "tnt4py" if args.topic: topic = args.topic publish.single(topic, args.msg, hostname=args.mqtt[0], auth={"username":args.mqtt[1], "password":args.mqtt[2]})
def iterateNodes(xbee, runningNodes, uniqueDict): # while True: print "in iterator nodes" for key in runningNodes: # InfoIdConv just sets the info_id as the destination address status = None t = 9999 #defaults to temperature sensor try: xbee.tx(frame_id='2', dest_addr=key, data='\x54\x3F\x0A') # xbee.tx(frame_id='2', dest_addr=key, data='\x4C\x3F\x0A') print '[WAITING ON DATA]' status=xbee.wait_read_frame(timeout=1) # if status['sdz']: # print "hi" print status print 'RECEIVED DATA]' status=xbee.wait_read_frame(timeout=1) print status t=status['rf_data'].split('/r/n')[0] t=t.split('\n')[0] t=t.split('=')[1] print 'RECEIVED RF DATA: ' + t mqttUploadString = ('testbed/' + key.encode('hex')) print "Sending message to broker on topic: " + mqttUploadString publish.single(mqttUploadString, t, hostname=BROKER_NAME) except: print "EXCEPTION IN ITERATE NODES"
def lo(): """ The program turns on LED """ # Set up logging syslog.syslog('Lo Starting') logging.basicConfig(filename='ha-conn.log',level=logging.DEBUG) logging.info('Lo starting') # set up the MQTT environment client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("127.0.0.1", 1883, 60) topic = "homeassistant/2/101/1/P" msgDict = {} msgDict['action'] = "P" msgDict['result'] = 0 msgDict['req_ID'] = 4 msgDict['deviceID'] = 101 msgDict['instance'] = 1 msgDict['float1'] = 300 msg = json.dumps(msgDict) print(topic + " " + msg) logging.info(topic + " " + msg) publish.single(topic, msg, hostname="127.0.0.1")
def send(uid, addr, req, token): broker = get_broker(addr) buf = codec.encode(req, token, uid) if QOS >= 0: publish.single(addr, buf, hostname=broker, port=SIGNALING_PORT, qos=QOS) else: publish.single(addr, buf, hostname=broker, port=SIGNALING_PORT)
def mqtt_monitor(): """ The main program that links the gateway Moteino to the MQTT system """ global reqList # set up the MQTT environment client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("127.0.0.1", 1883, 60) client.loop_start() req_Ref = 1 # a unique reference number to include in each request reqList = [] # a list to hold outstanding requests inpString = '' myReq = remoteRequest("") # create an empty request object myReq.topic = 'homeassistant/jim' myReq.node=1 myReq.device=1 myReq.instance=1 myReq.action='Z' myReq.result=12 myReq.float1=13 myReq.float2=14 myReq.req_ID=15 myReq.Topic() # Create the topic & message to send to mqtt myReq.Msg() while True: time.sleep(5) #publish.single(myReq.topic, myReq.msg, hostname="127.0.0.1") # send to mqtt # send to mqtt publish.single("Jim/topic", "Test", hostname="127.0.0.1") # send to mqtt # send to mqtt
def tearDown(self): # Kill the server publish.single("abort", payload="abort", hostname=config.mqtt_server, port=1883) # Wait long enough for it to shrivel up and DIE time.sleep(15)
def publish(self, msg): try: publish.single(topic=self.topic, payload=msg, hostname=self.host, auth=self.auth, tls=self.tls, port=self.port) #print "MQTT message published:", self.topic, msg, self.host, self.auth, self.tls, self.port logging.info( "MQTT message published: " + msg) except Exception, ex: logging.error(ex)
def handle(text, mic, profile): """ Responds to user-input, typically speech text, by sending a mosquitto publish event Arguments: text -- user-input, typically transcribed speech mic -- used to interact with the user (for both input and output) profile -- contains information related to the user (e.g., phone number) """ words = text.split(' ') if words[0] not in DEVICES: return mic.say(words[0]+" not found in the list of devices") if words[1] not in NUMBERS: return mic.say(words[1]+" not found in the list of valid indexes") if words[2] not in PAYLOADS: return mic.say(words[2]+" is not found in the list of valid payloads") topic = '/'.join(['hal9000']+words[0:2]) payload = words[2] if payload == 'OF': payload = 'OFF' if 'protocol' in profile['mqtt'] and profile['mqtt']['protocol'] == 'MQTTv311': protocol = mqtt.MQTTv311 else: protocol = mqtt.MQTTv31 publish.single(topic.lower(), payload=payload.lower(), client_id='hal9000', hostname=profile['mqtt']['hostname'], port=profile['mqtt']['port'], protocol=protocol)
def analyzer(response): result = {} res = [hex(i) for i in response] print len(res) result['header'] = header_analyser(res) result['command'] = command_analyzer(res) result['parameters'] = paramaters_analyzer(res) timestamp = datetime.now().time() print 'header: ' + str(antenna_code) print 'command: ' + result['command'] if len(res)>50: print '-'.join(res[26:42]) print 'Antenna: ' + str(antenna_code) #'-'.join(res[24:25]) print 'Tag: '+ '-'.join(res[26:42]) msg = json.dumps({'tag': '-'.join(res[26:42]), 'antenna': str(antenna_code) , 'timestamp': str(timestamp) }, sort_keys=True,indent=4, separators=(',', ': ')) try: publish.single("input/" + get_antenna_code(), msg , hostname="localhost", port=1883, client_id="", keepalive=60, will=None, auth=None, tls=None) print "LED ON" except: print "LED OFF" pass else: print '-'.join(result['parameters']) print '' return result
def publish_mqtt(payload): topic = "/plc1" try: publish.single(topic, payload, hostname="broker_ip_address", port=1883, retain=False, qos=0) except Exception as err: print "Couldn't publish :" + str(err) pass
def get_values(): while True: for index, host in enumerate(global_variables[service_name+"_datalogger_hosts"]): host = global_variables[service_name+"_datalogger_hosts"][index] name = global_variables[service_name+"_datalogger_names"][index] port = global_variables[service_name+"_datalogger_ports"][index] user = global_variables[service_name+"_datalogger_users"][index] password = global_variables[service_name+"_datalogger_passwords"][index] devices = global_variables[service_name+"_datalogger_devices"][index] xml = get_xml(host,port,user,password,devices) tree = ET.ElementTree(ET.fromstring(xml)) root = tree.getroot() for each_device in root: device_name = each_device.attrib["name"] for each_channel in each_device: channel_name = each_channel.attrib["des"] channel_magnitude = channel_name.split(" ")[0] channel_unit = channel_name[channel_name.find("(")+1:channel_name.find(")")] channel_value = standarize_unit(channel_unit,each_channel.text) topic_name = "%s/%s/%s/%s" %(global_variables[service_name+'_publish_topic_prefix'],name,device_name,channel_magnitude) try: print "Publishing topic '%s' with value '%s'" %(topic_name,channel_value) mqtt_publish.single(topic_name, channel_value, hostname=global_variables['global_mqtt_broker_host']) except: log("[%s] ERROR - Can't publish topic %s" %(datetime.datetime.now(),topic_name)) try: mqtt_publish.single(global_variables[service_name+'_publish_topic_prefix']+"/timestamp",time.strftime("%Y-%m-%d %H:%M:%S"), hostname=global_variables['global_mqtt_broker_host']) except: pass time.sleep(float(global_variables[service_name+'_data_interval']))
def broker(org,place,brokerIP,clientId): logger.debug(broker) info('broker') while True: publish.single(org + "/" + place + "/" + "internal/status/publish" , "0", hostname = brokerIP, client_id= clientId, will=None, auth=None,tls=None) logger.debug('Sleeping 12 sec') time.sleep(1.5) #seconds
def weather(): #pos = 0 #Tuesday : Showers and thunderstorms. Lows overnight in the low 70s. #Tuesday Night : Thunderstorms likely. Low 72F. Winds SSW at 5 to 10 mph. Chance of rain 90%. try: r = requests.get("http://api.wunderground.com/api/6eeded444749b8ec/forecast/q/10011.json") z = r.json() except Exception as e: print("Exception in weather", e) return #z = r.json() if not 'forecast' in z: print("'forecast' not in result of weather request") return try: forecast = z['forecast']['txt_forecast']['forecastday'] # if before 3 pm get today report and tomorrow report otherwise get tonight and tomorrow reports = (1,2) if datetime.datetime.now().hour > 15 else (0,2) text = [] for n in reports: text.append(forecast[n]['title'] + ': ' + forecast[n]['fcttext']) print(datetime.datetime.now()) print(repr(text).encode('ascii', 'ignore')) data = {"header":"Weather", "text":text, "pos":15, "dest":(1000,825)} except Exception as e: data = {"header":"Weather", "text":["Exception: {}".format(e)], "pos":15, "dest":(1000,825)} publish(payload=json.dumps(data)) mqtt_publish.single('esp_tft_display', payload=json.dumps(data), hostname=aws_host, retain=False, port=1883, keepalive=60)
def sales_forecast(): #forecast s = requests.Session() r = s.get("https://login.salesforce.com/?un={}&pw={}".format(sf_id, sf_pw)) #forecast r = s.get("https://na3.salesforce.com/00O50000003OCM5?view=d&snip&export=1&enc=UTF-8&xf=csv") content = r.content.decode('UTF-8') sf_data = csv.reader(StringIO(content)) sf_data = [row for row in sf_data if len(row)>10] if not sf_data: return sf_data.pop(0) forecast = sum(map(float, [row[11] for row in sf_data])) forecast = "${:,d}".format(round(forecast)) print("forecast =", forecast) #closed closed = sum(map(float, [row[10] for row in sf_data])) closed = "${:,d}".format(round(closed)) print("closed =", closed) data = {"header":"Forecast", "text":["forecast: {}".format(forecast), "closed: {}".format(closed)], "pos":5} #expects a list mqtt_publish.single('esp_tft', json.dumps(data), hostname=aws_host, retain=False, port=1883, keepalive=60)
def on_connect_state2(client2, userdata, rc): global nodeList # global state2Counter print "In state2 on connect message" for MacAddr in nodeList: print MacAddr publish.single("testbed/gateway/mqtt/" + MacAddr, GET_TYPE, hostname=BROKER_NAME)
def publish_single(self, topic, payload=None, qos=0, retain=False, hostname="localhost", port=1883, client_id="", keepalive=60, will=None, auth=None, tls=None, protocol=mqtt.MQTTv31): """ Publish a single message and disconnect. This keyword uses the [http://eclipse.org/paho/clients/python/docs/#single|single] function of publish module. `topic` topic to which the message will be published `payload` message payload to publish (default None) `qos` qos of the message (default 0) `retain` retain flag (True or False, default False) `hostname` MQTT broker host (default localhost) `port` broker port (default 1883) `client_id` if not specified, a random id is generated `keepalive` keepalive timeout value for client `will` a dict containing will parameters for client: will = {'topic': "<topic>", 'payload':"<payload">, 'qos':<qos>, 'retain':<retain>} `auth` a dict containing authentication parameters for the client: auth = {'username':"******", 'password':"******"} `tls` a dict containing TLS configuration parameters for the client: dict = {'ca_certs':"<ca_certs>", 'certfile':"<certfile>", 'keyfile':"<keyfile>", 'tls_version':"<tls_version>", 'ciphers':"<ciphers">} `protocol` MQTT protocol version (MQTTv31 or MQTTv311) Example: Publish a message on specified topic and disconnect: | Publish Single | topic=t/mqtt | payload=test | hostname=127.0.0.1 | """ logger.info('Publishing to: %s:%s, topic: %s, payload: %s, qos: %s' % (hostname, port, topic, payload, qos)) publish.single(topic, payload, qos, retain, hostname, port, client_id, keepalive, will, auth, tls, protocol)
def publish_mqtt(payload): topic = 'EPC/DATA1' try: publish.single(topic, payload, hostname=ip, port=1883, retain=False, qos=0) except Exception as err: print "Erro ao Criar o Topico: " + str(err) pass
def contingency_plan(contingency): global nodeList print "in contingency_plan" print nodeList # For each mac address (appliance) for i in nodeList: if contingency < 0: if nodeList[i] < abs(contingency): # Disable everything in the appliance countp1 = i.split(',')[1] # get A=X countp2 = countp1.split('=')[1] # get X j = 0 while j < int(countp2): publish.single("testbed/gateway/mqtt/" + i.split(',')[0], 'AO' + str(j) + '=0', hostname=BROKER_NAME) print 'AO' + str(j) j = j + 1 time.sleep(1) # Need to wait due to limitation of the arduino if contingency > 0: if nodeList[i] < abs(contingency): # Disable everything in the appliance countp1 = i.split(',')[1] # get A=X countp2 = countp1.split('=')[1] # get X j = 0 while j < int(countp2): publish.single("testbed/gateway/mqtt/" + i.split(',')[0], 'AO' + str(j) + '=1', hostname=BROKER_NAME) print 'AO' + str(j) j = j + 1 time.sleep(1)
def sendND(): try: while(True): publish.single("testbed/nodeDiscover/command/", 'START', hostname=BROKER_NAME) time.sleep(30) except: print "Publish ND command failed. Trying again in 30 seconds..."
def publish(self, msg): try: publish.single( topic=self.topic, payload=msg, hostname=self.host, auth=self.auth, tls=self.tls, port=self.port ) except Exception, ex: print ex
def checkEvent(onlyEv=False): if debug: print("[checkEvent]") global link_map #warte auf mouseup try: for ev in p.event.get(6): #hole coords pos = ev.pos if onlyEv: return True #vergleiche mit linkmap for ln in link_map: #fuehle ersten treffer aus if ln["pos1"][0] <= pos[0] and ln["pos2"][0] >= pos[0] and ln["pos1"][1] <= pos[1] and ln["pos2"][1] >= pos[1]: if debug: print(pos) print(ln) #exit() if "exec" in ln.keys(): call('bin/'+ln["exec"]) if "screen" in ln.keys(): updateScreen(ln["screen"]) if "mqttt" in ln.keys(): mospub.single(ln["mqttt"], payload=ln["mqttp"], hostname=c.mSERVER) #verwerfe rest return True except: pass return False
def sendmessage(request): Topic = request.REQUEST.get('topic','') Message = request.REQUEST.get('message','') if Topic =='' or Message =='': return HttpResponse(returnCode(1004))#"{'error':1004,'message':'missing some part'}") publish.single(Topic, Message,qos=2, hostname=Hostname,port=Port) return HttpResponse(returnCode(2000))#"{'error':2000,'message':'Success!'}")
def run(self, topic, message=None, qos=0, retain=False): if self._username: self._auth_payload = { 'username': self._username, 'password': self._password, } if self._ssl: if not self._ssl_cacert: raise ValueError('Missing "ssl_cacert" config option') if not self._ssl_cert: raise ValueError('Missing "ssl_cert" config option') if not self._ssl_key: raise ValueError('Missing "ssl_key" config option') self._ssl_payload = { 'ca_certs': self._ssl_cacert, 'certfile': self._ssl_cert, 'keyfile': self._ssl_key, } publish.single(topic, payload=message, qos=qos, retain=retain, hostname=self._hostname, port=self._port, client_id=self._client_id, keepalive=60, auth=self._auth_payload, tls=self._ssl_payload, protocol=self._protocol)
def mqtt_pub(self, topic, msg): params = { 'hostname' : self.mqttbroker, 'port' : self.mqttport, 'client_id' : self.mqttclient, 'qos' : self.mqttqos, 'retain' : self.mqttretain, } auth = None tls = None if self.mqttuser is not None: auth = { 'username' : self.mqttuser, 'password' : self.mqttpwd } self.stderr.write('publishing \'%s\' to [%s:%d]%s...' % (msg, self.mqttbroker, self.mqttport, topic)) mqtt.single(topic, msg, auth=auth, tls=tls, **params) self.stderr.write('success\n') self.stderr.flush()
def process(csv): """ Split the CSV, transform to OwnTracks JSON and publish via MQTT""" try: tst, lat, lon, soc, interval = csv.split(",") if int(tst) < 1: print "Ignoring zeroed results:", result payload = { "_type": "location", "tst": int(tst), "lat": float(lat), "lon": float(lon), "tid": device_id[-2:], "batt": float(soc), # State of Charge in % "_interval": int(interval), } mqtt.single( topic, json.dumps(payload), qos=2, retain=True, hostname=hostname, port=int(port), client_id=clientid, auth=auth, will=will, tls=tls, protocol=int(protocol), ) except Exception, e: print str(e)
def balance_thread(): if not os.path.isfile("mqtt_config.txt"): raise Exception("MQTT is not configured. " "Create mqtt_config.txt with first line mqtt server IP address and " "second line with user name and" "third line with your password and" "forth line with your topic for account balance.") with open("mqtt_config.txt") as fp: ip = fp.readline().strip() user = fp.readline().strip() password = fp.readline().strip() topic = fp.readline().strip() while True: balance = exchange.get_balance() publish.single(topic, payload="{0}".format(sum([coin['usdtValue'] for coin in balance])), qos=0, retain=True, hostname=ip, port=1883, client_id="", keepalive=60, will=None, auth={'username': user, 'password': password}, tls=None) time.sleep(20)
def publish_msg(args): print 'publish >>> topic:', args.topic, 'payload:', args.payload if args.username and args.password: auth = {'username':args.username, 'password':args.password} else: auth = None publish.single(args.topic, args.payload, hostname=args.host, port=args.port, auth=auth)
def send(self, notifier, subscriber, measurement): value = measurement.get_value() threshold = subscriber.get_setting('threshold') topic = subscriber.get_setting('topic') if threshold == '': publish.single(topic, str(value), hostname="localhost") elif value > float(threshold): publish.single(topic, str(value), hostname="localhost")
def mqtt_publish(self, topicinfo): print "test**************************" sttmp = str(topicinfo) topic = str("ericsson/iot/" + topicinfo["account"] + "/things/" + topicinfo["clientid"] + "/update/accepted") payload = topicinfo["data"] print topic print payload mqtt_publisher.single(topic, payload, hostname=self._host, port=self._port)
def publish_mqtt(flow): update_file(count) try: publish.single(("UNIVAS_TCC_2015/%s/waterFlow" % (mac_address)), \ ('{"mac_address":"%s","date":"%s","flow":"%.3f"}' % (mac_address, \ get_current_time(),flow)),qos=1, hostname=MQTT_HOST) except: pass
import time import Logger sense = SenseHat() x_pos = 0 y_pos = 7 white = (255, 255, 255) trail = (0, 0, 0) eater = (255, 255, 0) visited = None ipConnect = "localhost" startload = "Write 'ordered' to start\n" print(startload) publish.single("dat235/groupnine/joystick", payload=None, qos=0, hostname=ipConnect) publish.single("dat235/groupnine/start", startload, retain=True, qos=1, hostname=ipConnect) log = Logger.Logger("MQEater_event.log","Logging a PixelEater run") def allEaten(): global visited accum = 0 for x in range(0, 8): for y in range(0, 8): if visited[x][y]: accum += 1 return accum == 64
def on_message(client, userdata, msg): # print("Cart new message: " + msg.topic + " " + str(msg.payload)) global feedback global global_counter global is_finish global feedback_list global percentage_feedback_list global output_list global percentage_output_list global time_list global setpoint_list global percentage_setpoint_list global lock global test_start_time global test_end_time global scenario_counter global pid global counter_for_cache_auto_scaling global k_i global output global last_output global error global setpoint global last_feedback global cache_max_size global max_acd global long_term_list_acd global short_term_list_dcr global long_term_list_dcr global long_term_list_error_ratio global acd global pre_cache_max_size # live plotter global size, y_vec, line1 # compensated_feedback = 0.0 lock.acquire() message = str(msg.payload.decode("utf-8")) # print("\nArrived topic: %s" % msg.topic) # print("Arrived message: %s" % message) if msg.topic == "core/edge/" + SDC_id + "/feedback": # compute feedback global_counter += 1 counter_for_cache_auto_scaling += 1 print("\nGlobal counter: %s, cache_max_size: %s, setpoint: %s, pre_cache_max_size: %s" % (global_counter, format(cache_max_size, ","), format(setpoint, ","), format(pre_cache_max_size, ","))) feedback = float(message) error = float(setpoint) - feedback long_term_list_error_ratio.put(error/pre_cache_max_size*100) last_output = pid.last_pid_output pid.cyclic_compute_for_cache_capacity_auto_scaling(error, global_counter) output = pid.pid_output # live plot # rand_val = np.random.randint(0, (5 << 20)) print("current feedback: %s, current pid_output: %s, current cache_max_size: %s" % (format(feedback, ","), format(output, ","), format(cache_max_size, ","))) # print("pid_output: %s" % format(output, ",")) # Live plot for testing # y_vec[-1] = float(feedback) / pre_cache_max_size * 100 # output # line1 = lp.live_plotter(x_vec, y_vec, line1) # y_vec = np.append(y_vec[1:], 0.0) if global_counter > 1: # 1. estimate the amount of consumed data (acd) acd = float(last_feedback + last_output - feedback) print("last_feedback (%s) + last_output (%s) - feedback (%s) = The amount of consumed data (%s)" % (format(last_feedback, ","), format(last_output, ","), format(feedback, ","), format(acd, ","))) # Save current feedback last_feedback = feedback # put the acd in the list long_term_list_acd.put(acd) # print(list_acd.list) # 2. estimate data consumption rate (dcr) dcr = float(acd / cache_max_size) short_term_list_dcr.put(dcr) # print(short_term_list_dcr.list) long_term_list_dcr.put(dcr) # print(long_term_list_dcr.list) # Previously the maximum of the amount of consumed data in range of n was used, # BUT it is not proper to react to sudden change # n_max = max(list_acd.list) # Get Maximum value in range of n in the list of the amount of consumed data (acd) if acd > max_acd: max_acd = acd if counter_for_cache_auto_scaling > 8: # Get short-term and long-term moving averages of data consumption rate (dcr) short_term_ma_dcr = sum(short_term_list_dcr.list) / len(short_term_list_dcr.list) long_term_ma_dcr = sum(long_term_list_dcr.list) / len(long_term_list_dcr.list) # Get the moving average of the amount of consumed data (acd) long_term_ma_acd = sum(long_term_list_acd.list) / len(long_term_list_acd.list) # max_ma_acd = max(list_acd.list) # Set threshold (Minimum threshold of cache size) cache_max_size_threshold = long_term_ma_acd * (1 + long_term_ma_dcr) # RSME: Root Mean Square Error, In this case, n is 7 error_ratio_quared = [er ** 2 for er in long_term_list_error_ratio.list] mean_of_error_ratio_quared = sum(error_ratio_quared) / len(error_ratio_quared) rsme_val = np.sqrt(mean_of_error_ratio_quared) print("rsme_val: %s(%%)" % rsme_val) # save previous cache_max_size pre_cache_max_size = cache_max_size # It shows an downward tread when short-term average is smaller than long-term average. # 매번 바뀌면 안됨! 뭔가 장치가 필요함!! if short_term_ma_dcr < long_term_ma_dcr and max_acd < cache_max_size and rsme_val < 5: print("========== Data consumption rate is downward trend! Cache capacity auto-scaling" "(cache_max_size_threshold: %s, ma_acd: %s)" % (format(cache_max_size_threshold, ","), format(long_term_ma_acd, ","))) cache_max_size = cache_max_size - (cache_max_size - long_term_ma_acd) * 0.5 # cache_max_size = cache_max_size - ma_acd if cache_max_size < cache_max_size_threshold: cache_max_size = cache_max_size_threshold setpoint = cache_max_size * 0.9 pid.setpoint = setpoint pid.pid_output_max = cache_max_size # pid.initialize(setpoint=setpoint * 0.9, pid_output_max=cache_max_size, pid_output_min=0) # # keep current error, global_counter, and pid_output # pid.last_error = error # pid.last_counter = global_counter # pid.last_pid_output = output counter_for_cache_auto_scaling = 0 # pid = PIDController.PIDController(k_p=k_p, k_i=k_i, k_d=k_d, setpoint=cache_max_size * 0.9, # remaining_ratio_upto_the_max=0.1) # counter = 0 # elif short_term_ma_dcr > long_term_ma_dcr and max_acd > cache_max_size and rsme_val > 7: elif cache_max_size < cache_max_size_threshold: print("========== cache_max_size is lower than cache_max_size_threshold! Cache capacity auto-scaling") cache_max_size = cache_max_size_threshold setpoint = cache_max_size * 0.9 pid.setpoint = setpoint pid.pid_output_max = cache_max_size # pid.initialize(setpoint=setpoint, pid_output_max=cache_max_size, pid_output_min=0) # # keep current error, global_counter, and pid_output # pid.last_error = error # pid.last_counter = global_counter # pid.last_pid_output = output counter_for_cache_auto_scaling = 0 else: print("Short_term_ma_dcr (%s), long_term_ma_dcr (%s), max_acd (%s), cache_max_size (%s)" % (short_term_ma_dcr, long_term_ma_dcr, max_acd, cache_max_size)) # if pid.setpoint > 0: # compensated_feedback = feedback + output - (1 / counter) # / counter??? # if counter > 9: # pid.setpoint = CACHE_MAX_SIZE * 0.9 # target_utilization = output * pid.delta_time + feedback # compensated_feedback = feedback + output - (1 / counter) # / counter??? # compensated_feedback = (target_utilization - feedback) / pid.delta_time # compensated_feedback = target_utilization # print("Feedback: %s /// Output: %s /// Target_utilization: %s /// Compensated feedback: %s" % # (feedback, output, target_utilization, compensated_feedback)) # compensated_feedback = output # Value chart # feedback_list.append(compensated_feedback) # setpoint_list.append(pid.setpoint) # Percentage chart # feedback is lower than 0... problem # print("Output: %s" % output) if output > 0: # split and distribute data f = open("100MB.zip", "rb") data = f.read(int(output)) print("Cram %s of data" % len(data)) publish.single("core/edge/" + SDC_id + "/data", data, hostname=MQTT_HOST, port=MQTT_PORT, qos=2) # print("Cram %s of data" % int(output)) # publish.single("core/edge/" + SDC_id + "/data", int(output), hostname=MQTT_HOST, port=MQTT_PORT) else: print("Flow_control(Skip to send data)") publish.single("core/edge/" + SDC_id + "/flow_control", "Controlling flow", hostname=MQTT_HOST, port=MQTT_PORT, qos=2) feedback_list.append(feedback) percentage_feedback_list.append(feedback / pre_cache_max_size * 100) output_list.append(output) percentage_output_list.append(output / pre_cache_max_size * 100) setpoint_list.append(pid.setpoint) percentage_setpoint_list.append(pid.setpoint / pre_cache_max_size * 100) time_list.append(global_counter) elif msg.topic == "core/edge/" + SDC_id + "/init_for_testing": print("Initialize for testing") feedback_list = [] percentage_feedback_list = [] output_list = [] percentage_output_list = [] time_list = [] setpoint_list = [] percentage_setpoint_list = [] scenario_counter = int(msg.payload) print("Scenario Number: %s" % scenario_counter) feedback = 0 global_counter = 0 counter_for_cache_auto_scaling = 0 cache_max_size = (5 << 20) pre_cache_max_size = cache_max_size setpoint = cache_max_size * 0.9 pid.initialize(setpoint=setpoint, pid_output_max=cache_max_size, pid_output_min=0) print("Setpoint: %s" % pid.setpoint) pid.sample_time = SAMPLE_TIME test_start_time = time.time() feedback_list.append(0) percentage_feedback_list.append(0) output_list.append(0) percentage_output_list.append(0) setpoint_list.append(pid.setpoint) percentage_setpoint_list.append(pid.setpoint / cache_max_size * 100) time_list.append(0) publish.single("core/edge/" + SDC_id + "/start_testing", "Start!!", hostname=MQTT_HOST, port=MQTT_PORT, qos=2) elif msg.topic == "core/edge/" + SDC_id + "/done_to_test": print("A test is finished") test_end_time = time.time() file_name = str(scenario_counter) + "-" + time.strftime("%Y%m%d%H%M%S") + ".csv" print(file_name) full_path = os.path.join(os.path.join(".", "testlog"), file_name) print(full_path) error_square_list2 = [(percentage_feedback_list[i] - percentage_setpoint_list[i]) ** 2 for i in range(2, len(percentage_feedback_list))] variance2 = sum(error_square_list2) / (len(percentage_feedback_list) - 2) standard_deviation2 = variance2 ** 0.5 with open(full_path, 'w', newline='') as csvfile: writer = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) # print running time writer.writerow([test_start_time, test_end_time, test_end_time - test_start_time]) # print variance and stdev writer.writerow([variance2, standard_deviation2]) # print data for idx in range(len(feedback_list)): writer.writerow( [time_list[idx], percentage_feedback_list[idx], output_list[idx], percentage_setpoint_list[idx], feedback_list[idx], abs(feedback_list[idx] - pid.setpoint) / pid.setpoint * 100]) csvfile.close() # scenario_counter = scenario_counter % 4 + 1 elif msg.topic == "core/edge/" + SDC_id + "/all_test_complete": print("Test complete!!") is_finish = True else: print("Unknown - topic: " + msg.topic + ", message: " + message) lock.release()
def activate(self): publish.single("hermes/asr/startListening", '{"siteId": "default"}', hostname="localhost", port=1883)
import paho.mqtt.publish as publish publish.single("hello/world", '{"sensor":"clock","time":"12/05/2018 14:05:55","number":0}', hostname="iot.franciscocalaca.com")
def publish_alti_temp(data): publish.single("mobilenode/altitude", data[3], hostname="localhost") publish.single("mobilenode/temperature", data[5], hostname="localhost")
y_robot = (int(yc) - 500) #versturen naar de robot #msg = {"x" : x_robot, "y" : y_robot, "z" : 50} #print(json.dumps(msg, sort_keys=True, indent=4)) #publish.single(MQTT_ROBOT,payload=json.dumps(msg),hostname=MQTT_SERVER) timerBool = False #print("----------------------------------") #print("x center" + str(((x + (w/2))*expected)/1000) + "mm " + str(((x + (w/2))*expected)/10000000*expected) + "%") #print("y center" + str(((y + (h/2))*expected)/1000) + "mm " + str(((y + (h/2))*expected)/10000000*expected) + "%") #print("----------------------------------") print(stringCoordinaten) publish.single(MQTT_HOLO, payload=stringCoordinaten, hostname=MQTT_SERVER) cv2.namedWindow('RealSense5', cv2.WINDOW_NORMAL) cv2.resizeWindow('RealSense5', 640, 480) cv2.imshow('RealSense5', cv2.cvtColor(crop_img, cv2.COLOR_BGR2RGB)) #OVERLAY DEPTH MAP ON CAMERA #cv2.namedWindow('RealSense3', cv2.WINDOW_AUTOSIZE) #Transparancy = 0.5 #width = 640 #height = 480 #dim = (width, height) # resize image #resizedRGB = cv2.resize(crop_img, dim, interpolation = cv2.INTER_AREA) #resizedDepth = cv2.resize(colorized_depth, dim, interpolation = cv2.INTER_AREA)
def on_connect(client, userdata, flags, rc): """ Callback following connection to MQTT server """ client.username_pw_set(username=MQTT_USERNAME, password=MQTT_PASSWORD) print("Connected with result code " + str(rc)) def on_publish(client, userdata, result): """ Callback following message receipt by server """ print('Published to mqtt broker') client = mqtt.Client() client.on_connect = on_connect client.on_publish = on_publish client.connect(host=MQTT_HOST, port=MQTT_PORT) client.loop_start() client.publish(topic="test", payload="Testing raspberry pi", qos=1) client.loop_stop() client.disconnect single( topic=MQTT_TOPIC, payload="Testing", qos=MQTT_QOS, hostname=MQTT_HOST, port=MQTT_PORT, auth={'username':MQTT_USERNAME, 'password':MQTT_PASSWORD} )
def publishAll(message): publish.single(lancelot, message, hostname="192.168.1") publish.single(gawain, message, hostname="192.168.1") publish.single(percival, message, hostname="192.168.1")
t = sense.get_temperature() t = round(t) #print("temperature",t) return t def read_humidity(): h = sense.get_humidity() h = round(h) #print("humidity",h) return h def read_pressure(): p = sense.get_pressure() p = round(p) #print("pressure",p) return p def display_sensehat(message): sense.show_message(message) time.sleep(10) while True: sensor_data = [read_temp(), read_humidity(), read_pressure()] print("sending sensor data") publish.single("sensor", str(sensor_data), hostname="192.168.1.39") time.sleep(5)
wastingMult = 2 newsCost = True socCost = True if message == "Space": ISP = "SPACE ALERT\nRADIO" socMult = 2 newsMult = 2 shopCost = True clearScreens() printScreen(1, "Your Internet\nService Privider") printScreen(2, "Is now\n" + str(ISP)) printScreen(3, "Waiting for\nGame to start") isp1 = True else: publish.single(MQTT_PATH, message, hostname=MQTT_SERVER) if player == 2: isp2 = True if player == 3: isp3 = True if player == 4: isp4 = True if isp1 and isp2 and isp3 and isp4: startup = False time.sleep(2.0) publishAll("STARTUP") time.sleep(10.) printInventory() gameRunning = True
signal.signal(signal.SIGINT, end_read) # Create an object of the class MFRC522 MIFAREReader = MFRC522.MFRC522() # This loop keeps checking for chips. If one is near it will get the UID and authenticate while continue_reading: if not connected: sendConnectSignal() # Scan for cards (status, TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL) # If a card is found if status == MIFAREReader.MI_OK: print "Card detected" # Get the UID of the card (status, uid) = MIFAREReader.MFRC522_Anticoll() # If we have the UID, continue if status == MIFAREReader.MI_OK: # Print UID print "Card read UID: %s,%s,%s,%s" % (uid[0], uid[1], uid[2], uid[3]) # Publish UID to MQTT broker pub.single('sensors/RFID/raw', '%s,%s,%s,%s' % (uid[0], uid[1], uid[2], uid[3]), hostname='192.168.4.1')
"name": fan_name, "command_topic": mqtt_control_topic, "speed_state_topic": mqtt_state_topic, "speed_command_topic": mqtt_control_topic, "qos": 0, "payload_on": "auto", "payload_off": "1", "payload_low_speed": "10", "payload_medium_speed": "30", "payload_high_speed": "50", "speeds": ["off", "low", "medium", "high"] } json_template = json.dumps(config_template) mqtt_publish.single(config_topic, json_template, hostname=mqtt_host, client_id=mqtt_client_name, port=mqtt_port, retain=True) def on_connect(client, userdata, flags, rc): # The callback for when the client connects to the broker print("Connected with result code {0}".format( str(rc))) # Print result of connection attempt client.subscribe( mqtt_control_topic ) # Subscribe to the topic “digitest/test1”, receive any messages published on it def on_message(
def intent_request(session, request): intent = request['intent']['name'] print "intent_request: {}".format(intent) if intent == "PlayStation": station = request['intent']['slots']['mystation']['value'] mqtt_publish.single('sonos/' + location, json.dumps(dict(action='radio', station=station)), hostname=hostname, retain=False, port=1883, keepalive=60) output_speech = station + " radio will start playing soon" response = { 'outputSpeech': { 'type': 'PlainText', 'text': output_speech }, 'shouldEndSession': True } return response elif intent == "PlayAlbum" or intent == "AddAlbum": album = request['intent']['slots']['myalbum'].get('value', '') print "album =", album if album: s = 'album:' + ' AND album:'.join(album.split()) result = solr.search( s, fl='score,track,uri,album', sort='score desc', rows=25 ) #**{'rows':25}) #only brings back actual matches but 25 seems like max for most albums if result.docs: selected_album = result.docs[0]['album'] tracks = sorted([t for t in result.docs], key=itemgetter('track')) # The if t['album']==selected_album only comes into play if we retrieved more than one album uris = [ t['uri'] for t in tracks if t['album'] == selected_album ] action = 'play' if intent == "PlayAlbum" else 'add' mqtt_publish.single('sonos/' + location, json.dumps(dict(action=action, uris=uris)), hostname=hostname, retain=False, port=1883, keepalive=60) output_speech = "I will play {} songs from {}".format( len(uris), selected_album) end_session = True else: output_speech = "I couldn't find {}. Try again.".format(album) end_session = False else: output_speech = "I couldn't find the album. Try again." end_session = False response = { 'outputSpeech': { 'type': 'PlainText', 'text': output_speech }, 'shouldEndSession': end_session } return response elif intent == "PlayTrack" or intent == "AddTrack": # title must be present; artist is optional artist = request['intent']['slots']['myartist'].get('value', '') title = request['intent']['slots']['mytitle'].get('value', '') print "artist =", artist print "title =", title if title: s = 'title:' + ' AND title:'.join(title.split()) if artist: s = s + ' artist:' + ' AND artist:'.join(artist.split()) result = solr.search(s, rows=1) #**{'rows':1}) if len(result): track = result.docs[0] action = 'play' if intent == "PlayTrack" else 'add' mqtt_publish.single('sonos/' + location, json.dumps( dict(action=action, uris=[track['uri']])), hostname=hostname, retain=False, port=1883, keepalive=60) output_speech = "I will play {} by {} from album {}".format( track['title'], track['artist'], track['album']) end_session = True else: output_speech = "I couldn't find the song {} by {}. Try again.".format( title, artist) end_session = False else: output_speech = "I couldn't find the song. Try again." end_session = False response = { 'outputSpeech': { 'type': 'PlainText', 'text': output_speech }, 'shouldEndSession': end_session } return response elif intent == "Shuffle": shuffle_number = 10 artist = request['intent']['slots']['myartist'].get('value') if artist: s = 'artist:' + ' AND artist:'.join(artist.split()) result = solr.search(s, fl='uri', rows=500) count = len(result) if count: print "Total track count for {} was {}".format(artist, count) tracks = result.docs k = shuffle_number if shuffle_number <= count else count uris = [] for j in range(k): while 1: n = random.randint(0, count - 1) if count > shuffle_number else j uri = tracks[n]['uri'] if not uri in uris: uris.append(uri) break mqtt_publish.single('sonos/' + location, json.dumps(dict(action='play', uris=uris)), hostname=hostname, retain=False, port=1883, keepalive=60) output_speech = "I will play {} songs by {}.".format( shuffle_number, artist) end_session = True else: output_speech = "The artist {} didn't have any songs.".format( artist) end_session = False else: output_speech = "I couldn't find the artist you were looking for. Try again." end_session = False response = { 'outputSpeech': { 'type': 'PlainText', 'text': output_speech }, 'shouldEndSession': end_session } return response elif intent == "Deborah": # not in use number = request['intent']['slots']['number']['value'] mqtt_publish.single('sonos/' + location, json.dumps(dict(action='deborah', number=number)), hostname=hostname, retain=False, port=1883, keepalive=60) output_speech = "I will play " + str(number) + " of Deborah's albums" response = { 'outputSpeech': { 'type': 'PlainText', 'text': output_speech }, 'shouldEndSession': True } return response #elif intent == "WhatIsPlaying": # s3 = boto3.client('s3') # response = s3.get_object(Bucket='sonos-scrobble', Key='location') # body = response['Body'] # location = body.read() # dynamodb = boto3.resource('dynamodb', region_name='us-east-1') # table = dynamodb.Table('scrobble_new') # result = table.query(KeyConditionExpression=Key('location').eq(location), ScanIndexForward=False, Limit=1) #by default the sort order is ascending # if result['Count']: # track = result['Items'][0] # if track['ts'] > Decimal(time.time())-300: # output_speech = "The song is {}. The artist is {} and the album is {}.".format(track.get('title','No title'), track.get('artist', 'No artist'), track.get('album', 'No album')) # else: # output_speech = "Nothing appears to be playing right now, Steve" # else: # output_speech = "It appears that nothing has ever been scrobbled" # response = {'outputSpeech': {'type':'PlainText','text':output_speech},'shouldEndSession':True} # return response elif intent == "RecentTracks": # right now look back is one week; note can't limit because you need all the tracks since we're doing the frequency count payload = { 'method': 'user.getRecentTracks', 'user': '******', 'format': 'json', 'api_key': last_fm_api_key, 'from': int(time.time()) - 604800 } #, 'limit':10} try: r = requests.get(base_url, params=payload) z = r.json()['recenttracks']['track'] except Exception as e: print "Exception in get_scrobble_info: ", e z = [] if z: dic = {} for d in z: dic[d['album']['#text'] + '_' + d['name']] = dic.get( d['album']['#text'] + '_' + d['name'], 0) + 1 a = sorted(dic.items(), key=lambda x: (x[1], x[0]), reverse=True) current_album = '' output_speech = "During the last week you listened to the following tracks" # if you wanted to limit the number of tracks that were reported on, could do it here for album_track, count in a: #[:10] album, track = album_track.split('_') if current_album == album: line = ", {} ".format(track) else: line = ". From {}, {} ".format(album, track) current_album = album if count == 1: count_phrase = "" elif count == 2: count_phrase = "twice" else: count_phrase = str(count) + " times" output_speech += line + count_phrase else: output_speech = "I could not retrieve recently played tracks or there aren't any." response = { 'outputSpeech': { 'type': 'PlainText', 'text': output_speech }, 'shouldEndSession': True } return response elif intent == "AMAZON.NextIntent": mqtt_publish.single('sonos/' + location, json.dumps(dict(action='skip')), hostname=hostname, retain=False, port=1883, keepalive=60) response = { 'outputSpeech': { 'type': 'PlainText', 'text': 'skipped' }, 'shouldEndSession': True } return response elif intent == "AMAZON.PreviousIntent": mqtt_publish.single('sonos/' + location, json.dumps(dict(action='previous')), hostname=hostname, retain=False, port=1883, keepalive=60) response = { 'outputSpeech': { 'type': 'PlainText', 'text': 'previous' }, 'shouldEndSession': True } return response elif intent == "AMAZON.PauseIntent": mqtt_publish.single('sonos/' + location, json.dumps(dict(action='pause')), hostname=hostname, retain=False, port=1883, keepalive=60) response = { 'outputSpeech': { 'type': 'PlainText', 'text': 'I will pause' }, 'shouldEndSession': True } return response elif intent == "AMAZON.ResumeIntent": mqtt_publish.single('sonos/' + location, json.dumps(dict(action='resume')), hostname=hostname, retain=False, port=1883, keepalive=60) response = { 'outputSpeech': { 'type': 'PlainText', 'text': 'I will resume' }, 'shouldEndSession': True } return response #elif intent == "PauseResume": # pauseorresume = request['intent']['slots']['pauseorresume']['value'] # if pauseorresume in ('pause','stop'): # action = 'pause' # elif pauseorresume in ('unpause','resume'): # action = 'resume' # else: # action = None # if action: # send_sqs(action=action) # output_speech = "The music will {}".format(pauseorresume) # else: # output_speech = "I have no idea what you said." # response = {'outputSpeech': {'type':'PlainText','text':output_speech},'shouldEndSession':True} # return response elif intent == "TurnTheVolume": volume = request['intent']['slots']['volume']['value'] if volume in ('increase', 'louder', 'higher', 'up'): action = 'louder' elif volume in ('decrease', 'down', 'quieter', 'lower'): action = 'quieter' else: action = None if action: mqtt_publish.single('sonos/' + location, json.dumps(dict(action=action)), hostname=hostname, retain=False, port=1883, keepalive=60) output_speech = "I will make the volume {}".format(action) else: output_speech = "I have no idea what you said." response = { 'outputSpeech': { 'type': 'PlainText', 'text': output_speech }, 'shouldEndSession': True } return response else: output_speech = "I couldn't tell which type of intent request that was. Try again." response = { 'outputSpeech': { 'type': 'PlainText', 'text': output_speech }, 'shouldEndSession': False } return response
def publish_nfc(data): publish.single("nfcnode/tag", ('Abdil'), hostname="localhost") publish.single( "nfcnode/tagDate", ('Abdil at {: %H:%M:%S %Y-%b-%d}'.format(datetime.datetime.now())), hostname="localhost")
import paho.mqtt.publish as publish publish.single("topic1", "{'test':'true'}", hostname="localhost") publish.single("topic2", "{'test':'false'}", hostname="localhost")
def publish_localization(data): publish.single("d7node/localization", data, hostname="localhost")
def notify_door(resp, door): topic = 'doors/response/' + door publish.single(topic, resp, qos=2, auth=auth, hostname=broker)
fanON() z=1 elif temperature<maxTMP: setup() fanOFF() z=0 GPIO.cleanup(20) # print('Inundatie: {}'.format(inundatie)) payload_dict={"Temperature_in_degrees":round(temperature,2), "Humidity_level":round(humidity,2), "Flood":inundatie, "Glass_Break" :spargere, "Fire" : fire, "Light_level" :(light*1000), "Sound" : sound, "Fan_Power":z} message = "Flood " + str(inundatie) + " Glas_Break " + str(spargere) + "Fire " + str(fire) +"Light_level" +str(light*1000) +"Sound " +str(sound) print(payload_dict) try: publicare.single(MQTT_TOPIC,qos = 1,hostname = MQTT_HOST,payload = json.dumps(payload_dict)) except: GPIO.cleanup() cont=cont+1 if (cont==1): cont=0 local_save(message) time.sleep(10) except KeyboardInterrupt: GPIO.cleanup()
#import paho.mqtt.publish as publish #publish.single("paho/test/single", "payload=test_msg", hostname="192.168.122.131") import paho.mqtt.publish as publish import time i=1 while i < 1000: publish.single("Test/test", payload='test', hostname="192.168.122.131", auth = {'username':"******", 'password':"******"}) i += 1 time.sleep(1)
#!/usr/bin/env import paho.mqtt.client as mqtt import paho.mqtt.publish as publish import paho.mqtt.subscribe as subscribe import time import base64 #mqtt.enable_logger(logger=log1.txt) strMqttBroker = "57.117.25.20" strMqttBroker = "mosquitto" strMqttChannel = "imagedata" broker = "mosquitto" topic = "image" for j in range(7): time.sleep(0.5) with open("/tmp/face-" + str(j + 1) + ".jpg", "rb") as imageFile: payload = base64.b64encode(imageFile.read()) print "complete decoding" payload = str(j + 5) publish.single(strMqttChannel, payload, hostname=strMqttBroker, keepalive=0.5, port=1883)
# MQTT Publish Demo # Publish two messages, to two different topics import paho.mqtt.publish as publish publish.single("CoreElectronics/test", 2, hostname="test.mosquitto.org") publish.single("CoreElectronics/topic", "World!", hostname="test.mosquitto.org") print("Done")
import paho.mqtt.publish as publicar import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BOARD) GPIO.setup(38, GPIO.IN) variable = False while True: variable=GPIO.input(38) if variable == True: msg="insuficiente" publicar.single('topico_de_prueba', 'insuficiente', hostname='namacuix272.ddns.net') archivo2 = open("/home/pi/Documents/humedad1.txt", "w+") archivo2.write(str(msg)) archivo2.close() else: msg="correcta" publicar.single('topico_de_prueba', 'correcta ', hostname='namacuix272.ddns.net') archivo2 = open("/home/pi/Documents/humedad1.txt", "w+") archivo2.write(str(msg)) archivo2.close() time.sleep(0.5)
def pub_me(self): publish.single(self.path, self.msg, hostname=self.serv)
def front(operation="", segment="", value=''): #Verify the access level accessLevel = 0 try: authorization = request.headers['authorization'].split(' ')[1] savedToken = hData.getToken('front') savedAPIKey = hData.getToken('apikey') if authorization == savedAPIKey: accessLevel = 10 elif authorization == savedToken: accessLevel = 100 except: accessLevel = 0 #if authorization == savedToken or (not savedAPIKey == '' and savedAPIKey == authorization): responseData = {} if segment == "" or operation == "": responseData = { 'error': 'Bad request', 'code': 400, 'note': 'See the documentation' } else: #User doesn't require token if segment == 'user': if accessLevel >= 0: if operation == 'set': return hData.setUser(request.get_json()) elif operation == 'login': responseData = hData.login(request.headers) elif operation == 'validateToken': responseData = hData.validateUserToken(request.headers) elif operation == 'googleSync': return hData.googleSync(request.headers, responseURL) else: responseData = { 'error': 'Operation not supported', 'code': 400, 'note': 'See the documentation' } else: hData.log( 'Alert', 'Request to API > user endpoint with bad authentication') responseData = { 'error': 'Bad authentication', 'code': 401, 'note': 'See the documentation' } elif segment == 'global': if accessLevel >= 10: if operation == 'version': responseData = hData.getVersion() elif operation == 'get': responseData = hData.getGlobal() else: responseData = { 'error': 'Operation not supported', 'code': 400, 'note': 'See the documentation' } else: hData.log( 'Alert', 'Request to API > global endpoint with bad authentication') responseData = { 'error': 'Bad authentication', 'code': 401, 'note': 'See the documentation' } elif segment == 'devices': if accessLevel >= 10: if operation == 'update': incommingData = request.get_json() hData.updateDevice(incommingData) responseData = {'status': 'Success', 'code': 200} elif operation == 'create': incommingData = request.get_json() hData.createDevice(incommingData) responseData = {'status': 'Success', 'code': 200} elif operation == 'delete': hData.deleteDevice(value) responseData = {'status': 'Success', 'code': 200} elif operation == 'get': if not value == '': found = False for device in hData.getDevices(): if device['id'] == value: responseData = device found = True break if not found: responseData = { 'error': 'Device not found', 'code': 404, 'note': 'See the documentation' } else: responseData = hData.getDevices() else: responseData = { 'error': 'Operation not supported', 'code': 400, 'note': 'See the documentation' } else: hData.log( 'Alert', 'Request to API > devices endpoint with bad authentication' ) responseData = { 'error': 'Bad authentication', 'code': 401, 'note': 'See the documentation' } elif segment == 'status': if accessLevel >= 10: if operation == 'update': incommingData = request.get_json() hData.updateParamStatus(incommingData['id'], incommingData['param'], incommingData['value']) responseData = {'status': 'Success', 'code': 200} elif operation == 'get': status = hData.getStatus() if not value == '': if value in status: responseData = status[value] else: responseData = { 'error': 'Device not found', 'code': 404, 'note': 'See the documentation' } else: responseData = status else: responseData = { 'error': 'Operation not supported', 'code': 400, 'note': 'See the documentation' } else: hData.log( 'Alert', 'Request to API > status endpoint with bad authentication') responseData = { 'error': 'Bad authentication', 'code': 401, 'note': 'See the documentation' } elif segment == 'tasks': if accessLevel >= 10: if operation == 'update': incommingData = request.get_json() hData.updateTask(incommingData) responseData = {'status': 'Success', 'code': 200} elif operation == 'create': incommingData = request.get_json() hData.createTask(incommingData['task']) responseData = {'status': 'Success', 'code': 200} elif operation == 'delete': hData.deleteTask(value) responseData = {'status': 'Success', 'code': 200} elif operation == 'get': tasks = hData.getTasks() try: if not value == '': if 0 <= int(value) < len(tasks): responseData = tasks[int(value)] else: responseData = { 'error': 'Task not found', 'code': 404, 'note': 'See the documentation' } else: responseData = tasks except: responseData = { 'error': 'Invalid task ID, it must be a integer', 'code': 409, 'note': 'See the documentation' } else: hData.log( 'Alert', 'Request to API > task endpoint with bad authentication') responseData = { 'error': 'Bad authentication', 'code': 401, 'note': 'See the documentation' } elif segment == 'settings': if accessLevel >= 100: if operation == 'update': incommingData = request.get_json() hData.updateSecure(incommingData) responseData = hData.getSecure() elif operation == 'get': responseData = hData.getSecure() elif operation == 'apikey': if authorization == savedToken: hData.log('Warning', 'An API Key has been regenerated') responseData = {'apikey': hData.generateAPIKey()} else: responseData = { 'error': 'The operation can only be done by an admin user', 'code': 403, 'note': 'See the documentation' } else: hData.log( 'Alert', 'Request to API > settings endpoint with bad authentication' ) responseData = { 'error': 'Operation not supported', 'code': 400, 'note': 'See the documentation' } elif accessLevel >= 0: if not hData.getAssistantDone(): if operation == 'domain': if value == '': responseData = { 'error': 'A domain must be given', 'code': 400, 'note': 'See the documentation' } else: hData.setDomain(value) responseData = {'status': 'Success', 'code': 200} elif operation == 'setAssistantDone': hData.setAssistantDone() responseData = {'status': 'Success', 'code': 200} else: hData.log( 'Alert', 'Request to API > assistant endpoint. The assistant was configured in the past' ) responseData = { 'error': 'The assistant was configured in the past', 'code': 401, 'note': 'See the documentation' } else: hData.log( 'Alert', 'Request to API > assistant endpoint. The assistant was configured in the past' ) responseData = { 'error': 'Bad authentication', 'code': 401, 'note': 'See the documentation' } elif segment == 'system': if accessLevel >= 100: if operation == 'upgrade': # subprocess.run(["sudo", "systemctl", "start", "homewareUpgrader"], stdout=subprocess.PIPE) subprocess.run(["sudo", "sh", "bash/update.sh"], stdout=subprocess.PIPE) responseData = {'code': '200'} elif operation == 'status': # Try to get username and password try: mqttData = hData.getMQTT() if not mqttData['user'] == "": client.username_pw_set(mqttData['user'], mqttData['password']) publish.single("homeware/alive", "all", hostname="localhost", auth={ 'username': mqttData['user'], 'password': mqttData['password'] }) else: publish.single("homeware/alive", "all", hostname="localhost") except: publish.single("homeware/alive", "all", hostname="localhost") responseData = { 'api': { 'enable': True, 'status': 'Running', 'title': 'Homeware API' }, 'mqtt': { 'enable': True, 'status': 'Stopped', 'title': 'Homeware MQTT' }, 'tasks': { 'enable': True, 'status': 'Stopped', 'title': 'Homeware Task' }, 'redis': hData.redisStatus() } try: ts = int(time.time()) alive = hData.getAlive() if (ts - int(alive['mqtt'])) < 10: responseData['mqtt']['status'] = "Running" if (ts - int(alive['tasks'])) < 10: responseData['tasks']['status'] = "Running" except: print("fail") elif operation == 'restart': subprocess.run(["sudo", "sh", "bash/restart.sh"], stdout=subprocess.PIPE) responseData = {'code': '200'} elif operation == 'reboot': subprocess.run(["sudo", "reboot"], stdout=subprocess.PIPE) responseData = {'code': '200'} elif operation == 'shutdown': subprocess.run(["sudo", "poweroff"], stdout=subprocess.PIPE) responseData = {'code': '200'} else: responseData = { 'error': 'Operation not supported', 'code': 400, 'note': 'See the documentation' } else: hData.log( 'Alert', 'Request to API > system endpoint with bad authentication') responseData = { 'error': 'Bad authentication', 'code': 401, 'note': 'See the documentation' } elif segment == 'access': if accessLevel >= 100: if operation == 'update': print('update') # incommingData = request.get_json() # hData.updateSecure(incommingData) # responseData = hData.getSecure() elif operation == 'get': responseData = hData.getAccess() else: hData.log('Alert', 'Request to API > access endpoint.') responseData = { 'error': 'Bad authentication', 'code': 401, 'note': 'See the documentation' } elif segment == 'log': if accessLevel >= 100: if operation == 'get': responseData = hData.getLog() else: responseData = { 'error': 'Operation not supported', 'code': 400, 'note': 'See the documentation' } else: hData.log( 'Alert', 'Request to API > log endpoint with bad authentication') responseData = { 'error': 'Bad authentication', 'code': 401, 'note': 'See the documentation' } response = app.response_class(response=json.dumps(responseData), status=200, mimetype='application/json') return response
def motionSensor(channel): if GPIO.input(11): if tf.detect_cat(): publish.single("Food", "hungry", hostname="192.168.0.53")
def publish(topic, payload): mqtt_publish.single( topic, payload, hostname=os.environ['HOST_MQTT'], tls=tls, port=port)
if useSSLWebsockets: import ssl tTransport = "websockets" tTLS = { 'ca_certs': "/etc/ssl/certs/ca-certificates.crt", 'tls_version': ssl.PROTOCOL_TLSv1 } tPort = 443 # Create the topic string topic = "channels/" + channelID + "/publish/" + apiKey while (True): humidity, temperature = Adafruit_DHT.read_retry(11, 4) print("Temperature = %s Humidity = %s" % (temperature, humidity)) tPayload = "field1=" + str(temperature) + "&field2=" + str(humidity) time.sleep(10) try: publish.single(topic, payload=tPayload, hostname=mqttHost, port=tPort, tls=tTLS, transport=tTransport) except (KeyboardInterrupt): break except: print("There was an error while publishing the data.")
def run(): # try: # report = reportF016TH(time="2020-07-09 10:54:16", # model="SwitchDoc Labs F007TH Thermo-Hygrometer", # device=233, # modelnumber=5, # channel=3, # battery="OK", # temperature_F=72.100, # humidity=45, # mic="CRC") # print("report = " + report.json()) # reportis = reportIndoorSensor(time=report.time, # model=report.model, # device=report.device, # modelnumber=report.modelnumber, # channel=report.channel, # battery=report.battery, # temperature=tempFtoC(report.temperature_F), # humidity=report.humidity) # print("reportis = " + reportis.json()) # except ValidationError as err: # print(err.json()) # try: # report = reportFT020T(time="2020-11-22 06:40:15", # model="SwitchDoc Labs FT020T AIO", # device=12, # id=0, # batterylow=0, # avewindspeed=2, # gustwindspeed=3, # winddirection=18, # cumulativerain=190, # temperature=1011, # humidity=27, # light=1432, # uv=4, # mic="CRC") # print("report = " + report.json()) # reportws = reportWeatherSensor(report=report, # dailyrainfall = daily_rainfall.update(report.cumulativerain), # monthlyrainfall = monthly_rainfall.update(report.cumulativerain), # annualrainfall = annual_rainfall.update(report.cumulativerain) # ) # print("reportws = " + reportws.json()) # except ValidationError as err: # print(err.json()) # --------------------------------------------------------------------------------------------------------------------------------------------------------------- # 146 = FT-020T WeatherRack2, #147 = F016TH SDL Temperature/Humidity Sensor print("Starting Wireless Read") #cmd = [ '/usr/local/bin/rtl_433', '-vv', '-q', '-F', 'json', '-R', '146', '-R', '147'] cmd = [ '/usr/local/bin/rtl_433', '-q', '-F', 'json', '-R', '146', '-R', '147' ] # We're using a queue to capture output as it occurs try: from Queue import Queue, Empty except ImportError: from queue import Queue, Empty # python 3.x ON_POSIX = 'posix' in sys.builtin_module_names def enqueue_output(src, out, queue): for line in iter(out.readline, b''): queue.put((src, line)) out.close() # Create our sub-process... # Note that we need to either ignore output from STDERR or merge it with STDOUT due to a limitation/bug somewhere under the covers of "subprocess" # > this took awhile to figure out a reliable approach for handling it... p = Popen(cmd, stdout=PIPE, stderr=STDOUT, bufsize=1, close_fds=ON_POSIX) q = Queue() t = Thread(target=enqueue_output, args=('stdout', p.stdout, q)) t.daemon = True # thread dies with the program t.start() # --------------------------------------------------------------------------------------------------------------------------------------------------------------- pulse = 0 while True: #Other processing can occur here as needed... #sys.stdout.write('Made it to processing step. \n') try: src, line = q.get(timeout=1) # print(line.decode()) except Empty: pulse += 1 else: # got line pulse -= 1 sLine = line.decode() data = dict() topic = "" # print(sLine) # See if the data is something we need to act on... if ((sLine.find('F007TH') != -1) or (sLine.find('F016TH') != -1)): sys.stdout.write('WeatherSense Indoor T/H F016TH Found' + '\n') # data = parseF016TH(sLine) # schema = desert.schema(reportF016TH, meta={"unknown": EXCLUDE}) try: sys.stdout.write(sLine + '\n') report = reportF016TH.parse_raw(sLine) data = json.loads( reportIndoorSensor(time=report.time, model=report.model, device=report.device, modelnumber=report.modelnumber, channel=report.channel, battery=report.battery, temperature=tempFtoC( report.temperature_F), humidity=report.humidity).json()) topic = '/'.join( ['weathersense', 'indoorth', str(data.get('channel'))]) except ValidationError as err: print(str(err)) if ((sLine.find('FT0300') != -1) or (sLine.find('FT020T') != -1)): sys.stdout.write('WeatherSense WeatherRack2 FT020T found' + '\n') # data = parseFT020T(sLine) # schema = desert.schema(reportFT020T, meta={"unknown": EXCLUDE}) try: sys.stdout.write(sLine + '\n') report = reportFT020T.parse_raw(sLine) data = json.loads( reportWeatherSensor( report=report).json()).get('report') topic = '/'.join([ 'weathersense', 'weatherrack2', str(data.get('device')) ]) except ValidationError as err: print(str(err)) if topic: sys.stdout.write(json.dumps(data) + '\n') sys.stdout.write("Published to topic" + topic + '\n') # publish.single(topic.lower(), json.dumps( # data), hostname=cfg.broker_ip) publish.single(topic.lower(), json.dumps(data), hostname='home-assistant') sys.stdout.flush()
client.subscribe( LISTEN_TOPIC , qos=1) client.on_connect = on_connect client.on_disconnect = on_disconnect client.on_subscribe = on_subscribe ("","",LISTEN_TOPIC , qos) client.on_message = on_message client.on_publish = on_publish client.loop_forever() running = True while running: try: serveur_http() partiemqtt() except (KeyboardInterrupt, SystemExit): running = False print("Finish current jobs and shut down. If you need force exit use kill") publish.single(STATUS_TOPIC,"Offline", qos=0, retain=True, hostname=MQTT_ADRESS, port=MQTT_PORT, auth= {'username':MQTT_LOGIN, 'password':MQTT_PASS}) except Exception as e: print("Fatal error while executing worker command: %s", type(e).__name__) publish.single(STATUS_TOPIC,"Offline", qos=0, retain=True, hostname=MQTT_ADRESS, port=MQTT_PORT, auth= {'username':MQTT_LOGIN, 'password':MQTT_PASS}) raise e
help="Auth User", metavar='user', default='') parser.add_argument("--password", '-P', required=False, help="Auth Pass", metavar='password', default='') args = parser.parse_args() my_dict = { 'instruction': 'ACCESS', 'tag': str(args.tag), 'secure-key': str(args.key) } if (args.token): my_dict['token'] = args.token if (args.user and args.password): my_dict['user'] = args.user my_dict['password'] = args.password publish.single('boards/instructions/' + str(args.place) + '/' + str(args.door) + '', json.dumps(my_dict), hostname="localhost")