def test_get_latest_dweet_for(self): """`get_latest_dweet_for` should return a valid response. """ dweepy.dweet_for(self.my_thing_id, test_data) dweets = dweepy.get_latest_dweet_for(self.my_thing_id) check_valid_get_response(self, dweets)
def functionServicesDweet(): while True: time.sleep(5) dweepy.dweet_for('InternetOfThings101Dweet', {'Status':'1'}) print dweepy.get_latest_dweet_for('InternetOfThings101Dweet') time.sleep(5) dweepy.dweet_for('InternetOfThings101Dweet', {'Status':'0'}) print dweepy.get_latest_dweet_for('InternetOfThings101Dweet')
def test_get_latest_dweet_for_without_a_key(self): """`get_latest_dweet_for` without a key should raise an exception. """ try: dweepy.get_latest_dweet_for(self.my_thing_id) except dweepy.DweepyError as e: self.assertEqual(e.args[0], 'this thing is locked and requires a key') else: self.fail("shouldn't ever get called")
def test_get_latest_dweet_for_with_an_invalid_key(self): """`get_latest_dweet_for` with an invalid key should raise an exception. """ try: dweepy.get_latest_dweet_for(self.my_thing_id, key='badkey') except dweepy.DweepyError as e: self.assertEqual(e.args[0], 'the key you provided doesn\'t work with this thing') else: self.fail("shouldn't ever get called")
def functionDataSensor(): # netdata = psutil.net_io_counters() # data = netdata.packets_sent + netdata.packets_recv temp = sensTH.readTemperature() hum = sensTH.readHumidity() lig = sensL.value() dweepy.dweet_for('IoT'+DeviceID, {'Temp':str(temp), \ 'Hum':str(hum),'Lig':str(lig)}) print dweepy.get_latest_dweet_for('IoT'+DeviceID)
def ip_update_loop(secret, verbose): global last_ip secret = get_thing(secret) master_ip = "" while True: print("Getting master") try: d = dweepy.get_latest_dweet_for(secret) print(d) master_ip = d[0]['content']['master_ip'] break except Exception as e: print(e) time.sleep(random.randint(4, 30)) print("Master IP", master_ip) while True: if (last_ip != get_ip()): try: requests.get("http://%s:5555/ip/%s" % (master_ip, get_ip())) last_ip = get_ip() except: last_ip = "ha" time.sleep(3)
def lambda_handler(event, context): times = 0 while times < 15: response = dweepy.get_latest_dweet_for('thecore') temp = response[0]['content']['temperature'] hum = response[0]['content']['humidity'] insert_query = "INSERT INTO Weather (id_app, temperature, humidity) VALUES (%s, %s, %s)" cursor.execute(insert_query, (weather_id, temp, hum)) connection.commit() times += 1 time.sleep(58) query = "SELECT * FROM Weather WHERE id_app = '" + weather_id + "'" cursor.execute(query) weather = cursor.fetchall() transactionResponse = {} transactionResponse['Thing'] = 'thecore' transactionResponse['Description'] = '15m temperature and humidity data' transactionResponse['Data'] = [{'index':index+1,'temperature': str(data[2]), 'humidity': data[3]} for index, data in enumerate(weather)] responseObject = {} responseObject['statusCode'] = 200 responseObject['headers'] = {} responseObject['headers']['Content-Type'] = 'application-json' responseObject['body'] = json.dumps(transactionResponse) requests.post(webhook_url, data=json.dumps(transactionResponse), headers={'Content-Type':'application/json'}) return responseObject
def setup_platform(hass, config, add_devices, discovery_info=None): """Setup the Dweet sensor.""" import dweepy device = config.get('device') value_template = config.get(CONF_VALUE_TEMPLATE) if None in (device, value_template): _LOGGER.error('Not all required config keys present: %s', ', '.join(CONF_DEVICE, CONF_VALUE_TEMPLATE)) return False try: content = json.dumps(dweepy.get_latest_dweet_for(device)[0]['content']) except dweepy.DweepyError: _LOGGER.error("Device/thing '%s' could not be found", device) return False if template.render_with_possible_json_value(hass, value_template, content) is '': _LOGGER.error("'%s' was not found", value_template) return False dweet = DweetData(device) add_devices([ DweetSensor(hass, dweet, config.get('name', DEFAULT_NAME), value_template, config.get('unit_of_measurement')) ])
def leervalores(): try: datos=dweepy.get_latest_dweet_for('TesisTonnyAlvarado') return datos except: datos=[{'content':{"presion":0,"flujo":0.05,"nivel":10.16}}] return
def Xdata(self): try: thing = self.lineEdit.text() url = dweepy.get_latest_dweet_for(thing) dict = url[0] thingv1 = self.lineEdit_2.text() thingv2 = self.lineEdit_3.text() val1 = dict['content'][str(thingv1)] val2 = dict['content'][str(thingv2)] longdate = dict['created'] date = longdate[:10] stamptime = longdate[11:19] curs.execute("SELECT * FROM portrecord") conn.commit() curs.execute( "INSERT OR IGNORE INTO portrecord (Thingname, Thingvisual1, Value1, Thingvisual2, Value2, Time, Date)VALUES(?,?,?,?,?,?,?)", (thing, thingv1, val1, thingv2, val2, date, stamptime)) print('Done') conn.commit() except Exception as error: self.messagebox("INFO", "Fill all the Blanks")
def manager(): global busy global prev_goal # send goal to robot pub = rospy.Publisher(COMMAND_IOT_NAME, String, queue_size=10) # receive robot status report rospy.Subscriber(STATUS_IOT_NAME, String, callback) rospy.init_node('patrol_manager', anonymous=True) rate = rospy.Rate(1) command = None while not rospy.is_shutdown(): if not busy: try: command = dweepy.get_latest_dweet_for(COMMAND_IOT_NAME)[0]['content'] except(dweepy.DweepyError): pass if(CMD_STANDBY in command.keys()): rospy.loginfo("[patrol_manager] standing by...") pass if(CMD_GOTO in command.keys()): goal = command[CMD_GOTO] if(goal == prev_goal): rospy.loginfo("[patrol_manager] standing by...") busy = False else: busy = True prev_goal = goal pub.publish(goal) rospy.loginfo("[patrol_manager] send goal: " + goal + ". Waiting for status report from robot...") rate.sleep()
def update(self): """Get the latest data from Dweet.io.""" try: self.data = dweepy.get_latest_dweet_for(self._device) except dweepy.DweepyError: _LOGGER.warning("Device %s doesn't contain any data", self._device) self.data = None
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Dweet sensor.""" name = config.get(CONF_NAME) device = config.get(CONF_DEVICE) value_template = config.get(CONF_VALUE_TEMPLATE) unit = config.get(CONF_UNIT_OF_MEASUREMENT) if value_template is not None: value_template.hass = hass try: content = json.dumps(dweepy.get_latest_dweet_for(device)[0]["content"]) except dweepy.DweepyError: _LOGGER.error("Device/thing %s could not be found", device) return if value_template.render_with_possible_json_value(content) == "": _LOGGER.error("%s was not found", value_template) return dweet = DweetData(device) add_entities([DweetSensor(hass, dweet, name, value_template, unit)], True)
def setup_platform(hass, config, add_devices, discovery_info=None): """Setup the Dweet sensor.""" import dweepy device = config.get('device') value_template = config.get(CONF_VALUE_TEMPLATE) if None in (device, value_template): _LOGGER.error('Not all required config keys present: %s', ', '.join(CONF_DEVICE, CONF_VALUE_TEMPLATE)) return False try: content = json.dumps(dweepy.get_latest_dweet_for(device)[0]['content']) except dweepy.DweepyError: _LOGGER.error("Device/thing '%s' could not be found", device) return False if template.render_with_possible_json_value(hass, value_template, content) is '': _LOGGER.error("'%s' was not found", value_template) return False dweet = DweetData(device) add_devices([DweetSensor(hass, dweet, config.get('name', DEFAULT_NAME), value_template, config.get('unit_of_measurement'))])
def test(self): latest_controller_dweet = dweepy.get_latest_dweet_for(self._dweet_controller) self._last_dweet = dateutil.parser.parse(latest_controller_dweet[0]["created"]) print self._last_dweet while True: self.get_all_controller_dweets() time.sleep(5)
def update(self): """Gets the latest data from Dweet.io.""" import dweepy try: self.data = dweepy.get_latest_dweet_for(self._device) except dweepy.DweepyError: _LOGGER.error("Device '%s' could not be found", self._device) self.data = None
def update(self): """Get the latest data from Dweet.io.""" import dweepy try: self.data = dweepy.get_latest_dweet_for(self._device) except dweepy.DweepyError: _LOGGER.warning("Device %s doesn't contain any data", self._device) self.data = None
def update(self): """Get the latest data from Dweet.io.""" import dweepy try: self.data = dweepy.get_latest_dweet_for(self._device) except dweepy.DweepyError: _LOGGER.error("Device '%s' could not be found", self._device) self.data = None
def listenDweets(): for r in readers : dweet = dweepy.get_latest_dweet_for(r["dweet_id"]) if r['last_dweet'] != dweet[0]["created"]: print(dweet) try: sendRequestCheckQrcode(str(dweet[0]["content"]["user_id"]),r) except KeyError: print("no value QrCode") r['last_dweet'] = dweet[0]["created"]
def getlast(args): """get the last message from the queue""" logger.info('Getting the last message from %s', args.queue) try: jsonPayLoad = dweepy.get_latest_dweet_for(args.queue) except dweepy.DweepyError as e: logger.exception('Failed to get the last message from queue %s', args.queue) sys.exit(1) print json.dumps({jsonPayLoad[0]['created']: jsonPayLoad[0]['content']['message']})
def getlast(args): """get the last message from the queue""" logger.info('Getting the last message from %s', args.queue) try: jsonPayLoad = dweepy.get_latest_dweet_for(args.queue) except dweepy.DweepyError as e: logger.exception('Failed to get the last message from queue %s', args.queue) sys.exit(1) print json.dumps( {jsonPayLoad[0]['created']: jsonPayLoad[0]['content']['message']})
def get_report(thing, key): """ Get the latest dweet for a thing validated by a key. If validation fails, throws InvalidDweetError """ dweets = dweepy.get_latest_dweet_for(thing) if len(dweets) == 0: return None dweet = dweets[0] if not verify(key, dweet['content']): raise InvalidDweetError('verification failed') return dweet['content']['data']
def get_dweet_payload(thing_name, auth=""): # try: dweet_returns = dp.get_latest_dweet_for(thing_name) except dp.api.DweepyError as e: print('[pyMySerialThing] Dweep error. Error msg: {}'.format(str(e))) dweet_returns = [] # # Filter out the payload which does not match the key(dweet_auth) accept_payload = list(filter(lambda z: z['auth']==auth,\ filter(lambda y: 'auth' in y,\ map(lambda x: x['content'],dweet_returns)))) return list(map(lambda x: x['data'], accept_payload))
def getlast(args): """get the last message from the queue""" logger.info('Getting the last message from %s', args.queue) try: jsonPayLoad = dweepy.get_latest_dweet_for(args.queue) # except dweepy.DweepyError as e: except dweepy.DweepyError: logger.exception('Failed to get the last message from queue %s', args.queue) # FIXME Where does this exit come from? # Perhaps should be imported from sys? exit(1) print json.dumps({jsonPayLoad[0]['created']: jsonPayLoad[0]['content']['message']})
def dweet_add(add='hrishiopo',dw=None): global lastTime global g global curSpeed if(dw==None): dweet = dweepy.get_latest_dweet_for(add)[0] else: dweet=dw try: #print dweet a = (accelConv(float(dweet['content']['ax'])),accelConv(float(dweet['content']['ay']))\ ,accelConv(float(dweet['content']['az']))) if(not g): g = (accelConv(float(dweet['content']['xg'])),accelConv(float(dweet['content']['yg']))\ ,accelConv(float(dweet['content']['zg']))) # Correct for gravity a = np.subtract(a,g) #Get current time using regex shenanigans timelist = dweet['created'].split('T')[1].split('Z')[0].split(':') tsecs = 0.0 for i in range(0,len(timelist)): tsecs+=float(timelist[i])*(60**(2-i)) if(lastTime==None): lastTime=tsecs curSpeed=(0.0,0.0,0.0) return iA = a*(tsecs-lastTime) if(curSpeed==None): curSpeed = iA return curSpeed+=iA print "%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f" % (curSpeed[0],curSpeed[1],curSpeed[2],iA[0],iA[1],iA[2],a[0],a[1],a[2],g[0],g[1],g[2],tsecs) except (KeyError, TypeError): return
def goto(x, y): x, y = ROS_point(x, y) str_point = str(x) + ' ' + str(y) dweepy.dweet_for(COMMAND_IOT_NAME, {CMD_GOTO: str(x) + ' ' + str(y)}) while True: status = dweepy.get_latest_dweet_for(STATUS_IOT_NAME)[0]['content']['status'] if str_point in status: break time.sleep(1) standby() if(SUCCESS in status): return True else: return False
def run(): conn = sqlite3.connect("./test.db") cursor = conn.cursor() # This might take more than 15 minutes to complete consultar = lambda consulta: dweepy.get_latest_dweet_for(consulta) list = [] for i in range(1, 16): fila = consultar('thecore')[0]['content'] list.append({ 'hora': datetime.now(), "temperatura": fila["temperature"], "humedad": fila["humidity"] }) time.sleep(60) pd.DataFrame(list).to_sql('thecore', con=conn, if_exists='append') cursor.execute("Select * from thecore ORDER BY hora DESC") datos_resultado = datosbot(cursor.fetchall()) webhook(datos_resultado)
def get_results(): """ :return: """ try: dweet = dweepy.get_latest_dweet_for(DWEET_THING) results = json.loads(dweet[0]['content']['results']) except Exception as err: results = [{ "name": "UNKOWN", "last_start_time": "", "last_end_time": "", "status": 0, "status_message": err, "alert_level": "UNKNOWN", "latency": 0.0, "label": "error", "sort": 10 }] return results
def setup_platform(opp, config, add_entities, discovery_info=None): """Set up the Dweet sensor.""" name = config.get(CONF_NAME) device = config.get(CONF_DEVICE) value_template = config.get(CONF_VALUE_TEMPLATE) unit = config.get(CONF_UNIT_OF_MEASUREMENT) if value_template is not None: value_template.opp = opp try: content = json.dumps(dweepy.get_latest_dweet_for(device)[0]["content"]) except dweepy.DweepyError: _LOGGER.error("Device/thing %s could not be found", device) return if value_template.render_with_possible_json_value(content) == "": _LOGGER.error("%s was not found", value_template) return dweet = DweetData(device) add_entities([DweetSensor(opp, dweet, name, value_template, unit)], True)
def setup_platform(hass, config, add_devices, discovery_info=None): """Setup the Dweet sensor.""" import dweepy name = config.get(CONF_NAME) device = config.get(CONF_DEVICE) value_template = config.get(CONF_VALUE_TEMPLATE) unit = config.get(CONF_UNIT_OF_MEASUREMENT) value_template.hass = hass try: content = json.dumps(dweepy.get_latest_dweet_for(device)[0]['content']) except dweepy.DweepyError: _LOGGER.error("Device/thing '%s' could not be found", device) return False if value_template.render_with_possible_json_value(content) == '': _LOGGER.error("'%s' was not found", value_template) return False dweet = DweetData(device) add_devices([DweetSensor(hass, dweet, name, value_template, unit)])
def observe(): t = time.time() print 'Observe at time: ' + str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(t))) time.sleep(wait_time) # read = np.nan # while(read != np.nan): message = dweepy.get_latest_dweet_for(robot_sensor) read = message[0]['content']['CO2'] time = message[0]['created'] # time.sleep(5) print 'Reading: ' + read print 'Measure time: ' + time # data = pd.read_csv("Station_Data.csv",sep = " ", skiprows=1200000, parse_dates = [[0, 1]]) # data.columns = ['Time', 'Station_num', 'UV_index', 'PM01', 'CO2', 'Temperature', 'PM10', 'IR', 'Visibility', 'Humidity', 'Organic_vapor', 'PM25'] # data['time_stamp'] = data['Time'].apply(lambda x:datetime.datetime.strptime(x[1:20],"%Y-%m-%d %H:%M:%S")) # data = data[data.time_stamp > time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(t))] # data = data[data.Station_num == robot_sensor] # print str(data.shape[0]) + ' measurements' # print 'From ' + str(data['time_stamp'].iloc[0]) + ' to ' + str(data['time_stamp'].iloc[data.shape[0] - 1]) # print 'Average reading: ' + str(np.nanmean(data['CO2'])) return read
def get_addresses(secret): """Returns a list of all registered addresses and pings them and garbage collects stale addresses. """ secret = get_thing(secret) ips = [] try: d = dweepy.get_latest_dweet_for(secret) ips = d[0]['content']['ips'] print(ips) except Exception as e: print(e) gc = ips[:] rv = {} for ip in ips: url = api_root(ip) + "/ping" try: r = requests.get(url, timeout=2) j = r.json() if 'uuid' not in j: gc.remove(ip) rv[j['uuid']] = ip except: gc.remove(ip) dweepy.dweet_for(secret, {'ips': gc}) return rv
filename = os.getcwd() + "/Station_Data.csv" with open(filename, 'ab') as file: writer = csv.writer(file, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) order = [ 'UV_index', 'PM01', 'CO2', 'Temperature', 'PM10', 'IR', 'Visibility', 'Humidity', 'Organic_vapor', 'PM25' ] new_feed = [] for i in range(7): try: newl = dweepy.get_latest_dweet_for('CrestResearchData-' + str(i)) except: newl = None new_feed += [newl] while True: last_feed = deepcopy(new_feed) new_feed = [] for i in range(7): try: newl = dweepy.get_latest_dweet_for('CrestResearchData-' + str(i)) except: newl = None new_feed += [newl] for i in range(7): if (new_feed[i] is not None) and (last_feed[i] is None
#!/usr/bin/python import sys import time import sqlite3 import dweepy args = sys.argv pibox = args[1] db = sqlite3.connect('stay_or_go.db') while True: try: dweets = dweepy.get_latest_dweet_for(pibox) except: print("dweet.io oops..") time.sleep(1) continue for dweet in dweets: # get dweet data d_thing = str(dweet['thing']) d_timestamp = str(dweet['created']) d_content = dweet['content'] # extract frontend health status d_cputemp = str(d_content['cputemp']).replace("'", "°") frontend = (d_thing, d_timestamp, d_cputemp) # extract measurement data m_time = d_content['unixtime']
import dweepy as dp import numpy as np import matplotlib.pyplot as plt from scipy.integrate import quad x = dp.get_latest_dweet_for('accel') data = x[0]['content']['accx'] print(data) k = data.split(sep=',') k.pop(-1) val = list(map(int, k)) N = 11 hdn = [] for i in range(-5, 6): a, b = quad(lambda w: np.cos(w * i) + 1j * np.sin(w * i), -1 * np.pi / 4, 1 * np.pi / 4) hdn.append(a / 6.28) print(hdn) def fmag(y): yp = [] for i in range(len(y)): temp = 0 for j in range(len(hdn)): if (i - j >= 0): temp += hdn[j] * y[i - j] yp.append(temp) return yp
mad = (255.0, 0.0, 0.0) happy = (0.0, 255.0, 0.0) sorta_mad = (255.0, 255.0, 102) while True: led.fillOff() led.all_off() if datetime.now().hour < 10: print "sleepy time" sleep(60) continue mood = dweepy.get_latest_dweet_for('yourthing')[0]['content']['status'] print mood step = 0.01 if mood == 'failure': c = mad elif mood == 'warning': c = sorta_mad else: c = happy r, g, b = c if mood in ('success', 'warning'): print 'color range' level = 0.01 dir = step
def temperatura(): return dweepy.get_latest_dweet_for('thecore')[0]['content']['temperature']
import dweepy import json import time import MySQLdb # Read data from dweet and insert it to online MySQL database timestamp_prev = 0 while(1): data = dweepy.get_latest_dweet_for('icrowd') print data[0]['content']['location_id'], data[0]['content']['crowd_density'], data[0]['content']['time_stamp'] if(timestamp_prev >= data[0]['content']['time_stamp']): continue; # Connect to sql database db = MySQLdb.connect("localhost","root","root","icrowd" ) cursor = db.cursor() cursor.execute("""select * from crowd_data""") print cursor.fetchall() # Prepare SQL query to INSERT a record into the database. sql = """INSERT INTO crowd_data(location_id, crowd_density, time_stamp) VALUES(%s, %s, %s, %s)""" try: # Execute the SQL command cursor.execute(sql, (data[0]['content']['location_id'], data[0]['content']['crowd_density'] ,data[0]['content']['time_stamp'])) # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() # disconnect from server timestamp_prev = data[0]['content']['time_stamp'] # Validate whether data is inserted cursor.execute("""select * from crowd_data""")
led.on() # Check if on the robot network before we start network out = subprocess.check_output("iwgetid wlan0 --raw", shell=True) if out != b'TP-Link_5958_5G\n': switch_to_robot_network() led = LED(17) led2 = LED(5) led.on() led2.off() # Start with a status or make one try: response = dweepy.get_latest_dweet_for('misty') old_status = str(response[0]["created"]) print("START:", old_status) except: dweepy.dweet_for('misty', {'status': 'script_start'}) time.sleep(2) while True: try: time.sleep(1.5) response = dweepy.get_latest_dweet_for('misty') new_status = str(response[0]["created"]) print("NOW: ", new_status) if new_status != old_status: old_status = new_status print("Trigger Alarm")
self._last_dweet = last_create_date def start(self): logging.info(self._now() + "\n***************************************\nStarting Dweet Monitor\n") logging.debug( "Connecting to Cassandra on " + str(self._cassandra_host_names) + " / port: " + self._cassandra_host_port) try: cluster = Cluster(self._cassandra_host_names, port=int(self._cassandra_host_port)) self._cassandra_session = cluster.connect(self._cassandra_keyspace) except Exception, e: logging.error(e) logging.error("Connecting to Cassandra failed.") latest_controller_dweet = dweepy.get_latest_dweet_for(self._dweet_controller) self._last_dweet = dateutil.parser.parse(latest_controller_dweet[0]["created"]) print self._last_dweet # start with max sleep, if data is found, checks are increased to more often until data stops sleep_time = self._sleep_time while True: time.sleep(5) logging.debug("Checking for new Dweets from Controller...") self.get_all_controller_dweets() logging.debug("Checking for new Dweets from drones...") for drone in self.active_drones.keys(): self._get_all_dweets(drone) def test(self): latest_controller_dweet = dweepy.get_latest_dweet_for(self._dweet_controller)
def test_get_latest_dweet_for_with_a_valid_key(self): """`get_latest_dweet_for` with a valid key should return a valid response. """ dweepy.dweet_for(self.my_thing_id, test_data, key=test_key) dweets = dweepy.get_latest_dweet_for(self.my_thing_id, key=test_key) check_valid_get_response(self, dweets)
import dweepy import json import time import os from gtts import gTTS tts = gTTS('pay attention to me') tts.save('sound.mp3') while True: try: with open('need_token.txt', 'r') as myfile: file_data = myfile.read() dweet = dweepy.get_latest_dweet_for('The_megan_beacon') value = str(dweet[0]["content"]["value"]) if file_data == value: print("yep") time.sleep(10) else: print("nope") # play audio file # write new number to token file print(value) os.system("afplay sound.mp3") with open('need_token.txt', 'w') as myfile: myfile.write(str(value)) print("updated old value " + file_data + " file with " + value) time.sleep(10) except: print("there was nothing there") time.sleep(10)
def humedad(): return dweepy.get_latest_dweet_for('thecore')[0]['content']['humidity']
def functionServicesDweet(): while True: dweepy.dweet_for('LightIoT', {'Value': functionDataSensor()}) print dweepy.get_latest_dweet_for('LightIoT') time.sleep(5)
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters import dweepy datos=dweepy.get_latest_dweet_for('TesisTonnyAlvarado') # print datos[0]['content']['presion'] print 'Presion = %6f bares'%(datos[0]['content']['presion']) print 'Flujo = %6f m/s'%(datos[0]['content']['flujo']) print 'Nivel = %6f in'%(datos[0]['content']['nivel'])