def process_response(session, response): #print("Calling process_response") print("------------- ") #print(response.content) data = response.content ip_addr = str(urlparse(response.url).hostname) #print(ip_addr) data_decode = data.decode('utf-8') if data_decode == '': data_decode = json.dumps({}) try: if (ip_addr in ip_dict): new_message = json.dumps({ "device_name": ip_dict[ip_addr], "ip_addr": ip_addr, "data": data_decode }) print("Received from " + ip_dict[ip_addr]) #print(new_message) r.publish('http-events', new_message) else: if (data_decode != "success\n"): print("Message of unknown") print(data_decode) print(response.content) except Exception as ex: print("Could not parse message.") print(ip_addr) print(data_decode) print(ex) raise return
def filtro_tiempo(self, tiempo): print("Filtro tiempo") r.publish( 'commands', json.dumps({ "device_name": "caja_filtro_alberca", "command": "turn_on", "value": "bomba", "origin": "webapp" })) mensaje_off = json.dumps({ "device_name": "caja_filtro_alberca", "command": "turn_off", "value": "bomba", "origin": "webapp" }) r.publish( 'commands', json.dumps({ "device_name": "timer_1", "command": "add_timer", "interval": 60 * 60 * float(tiempo), "value": mensaje_off, "origin": "webapp" })) return "Ciclo filtrado (3hrs)"
def main(): cache = dict() exec_channel = "execution" entry_channel = "entry" entry_send_channel = "entry_send" pubsub = r.pubsub() pubsub.subscribe(entry_channel, exec_channel) #print 'Listening to {channel}'.format(**locals()) while True: for item in pubsub.listen(): if item['data'] == 1L or item['data'] == 2L: continue if item['channel'] == "entry": print item['data'], "sent by order entry and cached" loaded_json = json.loads(item['data'].replace("\'", '"')) json_cache(loaded_json, cache) if item['channel'] == "execution": print item['data'], " sent by execution links" loaded_json = json.loads(item['data'].replace("\'", '"')) if loaded_json['order_id'] in cache: r.publish(entry_send_channel, str(cache[loaded_json['order_id']])) else: r.publish(entry_send_channel, "not found")
def regar_jardin(self, **kwargs): zona = kwargs.get('zona', None) tiempo = kwargs.get('tiempo', None) comm = {} if (tiempo == 0): comm = { "device_name": "caja_riego_jardin", "value": zona, "command": "turn_off", "pars": {}, "origin": "webapp" } else: comm = { "device_name": "caja_riego_jardin", "value": zona, "command": "turn_on", "pars": { "tiempo": int(tiempo) }, "origin": "webapp" } message = json.dumps(comm) r.publish('commands', message) return "Comando de riego enviado"
def main(): channel = "entry" print 'Welcome to {channel}'.format(**locals()) while True: message = raw_input('Enter a message: ') message = '{message}'.format(**locals()) if message.lower() == 'exit': break r.publish(channel, message)
def on_send(): msg = str(ui.textEdit_2.toPlainText()) # Check if the message is not empty if len(msg) > 0: usrname = str(ui.lineEdit.text()) if len(usrname) == 0: usrname = '<Anonymous>' channel = str(ui.comboBox.currentText()) ui.textEdit_2.clear() message = '%s [%s]: %s' % (usrname, channel, msg) # Publish the message into the Pub/Sub sub-system r.publish(channel, message)
def ring(self, lugar): print("ring") #r.publish('commands', json.dumps({'device_name':'sonos', # 'command':'play','value':'store_bell.wav', # 'volume':100, 'zone':'Estudio' })) r.publish( 'events', json.dumps({ 'device_name': 'caja_cocina_timbre', 'event_type': 'timbre', 'value': True })) return 'Ring!!'
def autoluz(self): message_say = json.dumps({ 'device_name': 'sonos', 'command': 'say', 'value': 'Auto luces' }) r.publish('commands', message_say) #con = lite.connect('/Volumes/mmshared/bdatos/comandos.db') #with con: # cur = con.cursor() # commandx = "INSERT INTO pendientes VALUES('auto_luces','0')" # cur.execute(commandx) return 'Auto luces'
def regar(self, sw): mensaje = 'Sistema de goteo' + str(sw) if (sw == '1'): r.publish( 'commands', json.dumps({ "device_name": "caja_goteo", "command": "turn_on", "value": "regar", "origin": "webapp" })) #r.publish('commands', json.dumps({"device_name":"sonos", # "command":"say", "value":"Regando ahora", "origin":"webapp"})) message_off = json.dumps({ 'device_name': 'caja_goteo', 'command': 'turn_off', 'value': 'regar', "origin": "timer" }) r.publish( 'commands', json.dumps({ "device_name": "timer_1", "command": "add_timer", "interval": 60 * 30, "value": message_off, "origin": "webapp" })) #app_timer.add_timer((20, json.dumps({"device_name":"caja_goteo", # "command":"turn_off", "value":"regar"}))) if (sw == '0'): r.publish( 'commands', json.dumps({ 'device_name': 'caja_goteo', 'command': 'turn_off', 'value': 'regar', "origin": "webapp" })) r.publish( 'commands', json.dumps({ "device_name": "sonos", "command": "say", "value": "Riego apagado", "origin": "webapp" })) # con = lite.connect('/Volumes/mmshared/bdatos/comandos.db') # with con: # cur = con.cursor() # if(sw=='1'): # commandx = "INSERT INTO pendientes VALUES('regar','1')" # mensaje ='Regar patio' # if(sw=='0'): # commandx = "INSERT INTO pendientes VALUES('regar','0')" # mensaje = 'Dejar de regar patio' # cur.execute(commandx) cherrypy.response.status = 200 return mensaje
def send_event(self, event_type, value): ip_origin = cherrypy.request.remote.ip if (ip_origin in ip_dict.keys()): device_name = ip_dict[ip_origin] else: device_name = 'unknown' if (value == 'True'): value = True ev = { 'device_name': device_name, 'event_type': event_type, 'value': value } r.publish('events', json.dumps(ev)) return json.dumps(ev)
def filtro_alberca(self, sw): if (sw == '0'): r.publish( 'commands', json.dumps({ "device_name": "caja_filtro_alberca", "command": "turn_off", "value": "bomba", "origin": "webapp" })) if (sw == '1'): r.publish( 'commands', json.dumps({ "device_name": "caja_filtro_alberca", "command": "turn_on", "value": "bomba", "origin": "webapp" })) return 'Bomba alberca'
def garage(self): mensaje = 'Activando garage' r.publish( 'commands', json.dumps({ "device_name": "caja_garage", "command": "activate", "value": "garage", "origin": "webapp" })) r.publish( 'commands', json.dumps({ "device_name": "sonos", "command": "say", "value": "Puerta de garage activada" })) r.publish( 'commands', json.dumps({ "device_name": "pushover", "command": "send_message", "value": "Puerta de garage activada" })) return mensaje
def lampara_tv(self, **kwargs): command = kwargs.get('command', None) comm = {} if (command == 'turn_off'): comm = { "device_name": "caja_tv", "value": "lampara", "command": "turn_off", "pars": {}, "origin": "webapp" } else: comm = { "device_name": "caja_tv", "value": "lampara", "command": "turn_on", "pars": {}, "origin": "webapp" } message = json.dumps(comm) r.publish('commands', message) return ""
def detecta_movimiento(self, sw): mensaje = 'Detector mov ' + str(sw) if (sw == '1'): r.publish( 'commands', json.dumps({ "device_name": "cam_entrada", "command": "set_motion_detect", "value": "on", "origin": "webapp" })) r.publish( 'commands', json.dumps({ "device_name": "cam_patio", "command": "set_motion_detect", "value": "on", "origin": "webapp" })) #app_timer.add_timer((20, json.dumps({"device_name":"caja_goteo", # "command":"turn_off", "value":"regar"}))) if (sw == '0'): print("apagando") r.publish( 'commands', json.dumps({ "device_name": "cam_entrada", "command": "set_motion_detect", "value": "off", "origin": "webapp" })) r.publish( 'commands', json.dumps({ "device_name": "cam_patio", "command": "set_motion_detect", "value": "off", "origin": "webapp" })) return mensaje
from settings import r import sys if __name__ == '__main__': name = sys.argv[1] channel = sys.argv[2] print 'Welcome to {channel}'.format(**locals()) while True: message = raw_input('Enter a message: ') if message.lower() == 'exit': break message = '{name} says: {message}'.format(**locals()) r.publish(channel, message)
import time as t from random import randint import datetime if __name__ == '__main__': channel = sys.argv[1] print 'Welcome to {channel}'.format(**locals()) while True: cpuA = randint(0, 100) cpuB = randint(0, 100) time = datetime.datetime.fromtimestamp( t.time()).strftime('%Y-%m-%d %H:%M:%S') message = "C1|" + str(time) + "|" + str(cpuA) + "|" + str(cpuB) print message r.publish(channel, message) message = "C2|" + str(time) + "|" + str(cpuA) + "|" + str(cpuB) print message r.publish(channel, message) message = "B|" + str(time) + "|" + str(cpuA) + "|" + str(cpuB) print message r.publish(channel, message) message = "ng|Outbound|Main|" + str(cpuA) r.publish(channel, message) t.sleep(1) message = "ng|ARP-Proxy|Inbound|" + str(cpuB) message = "network_graph|Main|BGP-Proxy|bgp|20" r.publish(channel, message)
def monitor(): p = r.pubsub() p.subscribe('xbee-commands') print("Activar xbee coordinator...") try: serialConnection = serial.Serial(SERIAL_PORT, 9600, timeout=0.15) xbee = ZigBee(serialConnection) print("Conexión xbee serial...OK") except: e = sys.exc_info()[0] print("Error: %s" % e) logging.warning('Error connecting serial/xbee') print("Error connecting serial/xbee") print('Iniciar ciclo') while True: response = {} response = xbee.wait_read_frame(timeout=0.15) if (len(response) > 0 and response['id'] != 'tx_status'): #print(response) response['source_addr_long'] = response['source_addr_long'].hex() response['source_addr'] = response['source_addr'].hex() #if(xbee_dict[response['source_addr_long']]=='caja_estudiof'): #if(xbee_dict[response['source_addr_long']]=='cajacocina'): if (True): print(response) print(response['source_addr_long']) print(xbee_dict[response['source_addr_long']]) print("") if ('rf_data' in response.keys()): try: response['rf_data'] = response['rf_data'].decode('utf-8') message = json.dumps({ 'device_type': 'xbeebox', 'device_name': xbee_dict[response['source_addr_long']], 'source': response['source_addr_long'], 'type': 'rf_data', 'content': response['rf_data'] }) r.publish('xbee-events', message) #if(json.loads(message)['device_name']=='cajarecamara'): # print('\a') except: print("Error decoding xbee message") if ('samples' in response.keys()): #response['samples'] = response['rf_data'].decode('utf-8') message = json.dumps({ 'device_type': 'xbeebox', 'device_name': xbee_dict[response['source_addr_long']], 'source': response['source_addr_long'], 'type': 'samples', 'content': response['samples'] }) r.publish('xbee-events', message) message = p.get_message() if (message and message['type'] == 'message'): print(message) message_in = json.loads(message['data'].decode('utf-8')) print(message_in) if message_in: dest_addr_long = unhexlify(message_in['addr_long']) if message_in['mode'] == 'tx': #dest_addr = message_in['source_addr'] data = str.encode(message_in['data']) print("Transmit tx") print(data) xbee.tx(dest_addr_long=dest_addr_long, data=data) #xbee.tx(dest_addr_long=b'\x00\x13\xa2\x00\x40\xbf\x96\x2c',dest_addr='\x40\xb3', data=b'1') if message_in['mode'] == 'pin': command = hexlify(bytes.fromhex(message_in['command'])) print("Transmit xbee pin change") print(dest_addr_long) print(command) parameter = bytes.fromhex(message_in['parameter']) print(parameter) xbee.remote_at(dest_addr_long=dest_addr_long, command=command, parameter=parameter)
#!/usr/bin/env python3 from settings import r import sys import time import redis if __name__ == '__main__': r.set('lab', 'sjtu-medialab') print(r.get('lab')) job_id = 0 socket_id = 0 topic = "JOB_FINISH" while True: r.publish(topic, str(job_id)) job_id += 1 time.sleep(2)