def sendToM2X(serial_id, name, data): # 設定の取得 ini = ConfigParser.SafeConfigParser() ini.read("uploads/" + serial_id + "/m2xconfig.ini") # 起動時に設定を取得 client_key_str = ini.get("device", "m2x_client_key") device_str = ini.get("device", "m2x_device") #print client_key_str #print device_str # M2Xの設定 try: client = M2XClient(client_key_str) device = client.device(device_str) for key, value in device.stream: client.stream('value') = device.stream('value') #client.stream_temperature = device.stream('temp') except: print "M2X not connected:", sys.exc_info()[0], sys.exc_info()[1] # データ送信 try: stream = device.stream(name) stream.add_value(data) except: print "M2X send error:", sys.exc_info()[0], sys.exc_info()[1]
def post_stock_price(symbol, apikey, devicename): ''' Retrieve the stock price for the given ticker symbol ("T" for AT&T) and post it in the correct M2X data stream. ''' client = M2XClient(key=apikey) # Find the correct device if it exists, if not create it. try: device = [ d for d in client.devices(q=devicename) if d.name == devicename ][0] except IndexError: device = client.create_device(name=devicename, description="Stockreport Example Device", visibility="private") # Get the stream if it exists, if not create the stream. try: stream = device.stream(symbol) except HTTPError: stream = device.create_stream(symbol) device.update_stream(symbol, unit={'label': 'Dollars', 'symbol': '$'}) postime = datetime.now() stock_price = ystockquote.get_price(symbol).encode('utf-8') stream.add_value(stock_price, postime)
def setup_class(self): httpretty.register_uri(httpretty.GET, self.DATA['devices']['device']['url'], body=json.dumps( self.DATA['devices']['device']['response']), content_type='application/json') self.client = M2XClient(key=self.TEST_KEY, api=APIVersion2) self.device = self.client.device(id='device1')
def setup_class(self): data = self.DATA['distributions']['distribution'] httpretty.register_uri(httpretty.GET, data['url'], body=json.dumps(data['response']), content_type='application/json') self.client = M2XClient(key=self.TEST_KEY, api=APIVersion2) self.distribution = self.client.distribution(id='distribution1')
def setup_class(self): data = self.DATA['keys']['key'] httpretty.register_uri(httpretty.GET, data['url'], body=json.dumps(data['response']), content_type='application/json') self.client = M2XClient(key=self.TEST_KEY) self.key = self.client.key('key1')
def PutValuesM2X(self,stream_id,data): client = M2XClient(key=self.APIkey) device = client.device(self.deviceID) #登録されているセンサならexceptを通り抜け、既存のストリームにデータを投入します try: stream=device.stream(stream_id) #登録されていないセンサのデータを受信した場合、新しいストリームを製作してそこにデータを投入します except HTTPError as error: stream=device.create_stream(name=stream_id) stream.add_value(data)
def handle(data_source_name, data_name, value): global ini stream_id = ini.get("stream", data_name) if stream_id is not None: client_id = ini.get("client", "key") device_id = ini.get("device", "key") if client_id is not None and client_id is not None: client = M2XClient(key=client_id) device = client.device(device_id) stream = device.stream(stream_id) print(stream.add_value(value))
def callback(path): try: api = CloudAppAPI(Config.get('cloudapp', 'username'), Config.get('cloudapp', 'password')) url = api.upload(path) print 'Public URL: ' + url client = M2XClient(Config.get('m2x', 'api_key')) stream = client.device(Config.get('m2x', 'device_id')).stream(Config.get('m2x', 'stream')) result = stream.add_value(url) print "Posted URL to M2X stream %s" % Config.get('m2x', 'stream') except HTTPError, e: print 'ERROR: ' + e.message
def setup_class(self): device = self.DATA['streams']['device'] stream = self.DATA['streams']['stream'] httpretty.register_uri(httpretty.GET, device['url'], body=json.dumps(device['response']), content_type='application/json') httpretty.register_uri(httpretty.GET, stream['url'], body=json.dumps(stream['response']), content_type='application/json') self.client = M2XClient(key=self.TEST_KEY, api=APIVersion2) self.device = self.client.device('device1') self.stream = self.device.stream('stream1')
def get_devices(): client = M2XClient(key=M2X_KEY) page_of_devices = client.devices() number_of_pages = client.last_response.json['pages'] devices = [] for page in range(1, number_of_pages + 1): for device in page_of_devices: devices.append([ device.name, json.dumps({ 'name': device.name, 'id': device.id }) ]) next_page = page + 1 page_of_devices = client.devices(page=next_page) return devices
def __init__(self, boot): self._boot = boot self._last_time = 0 self._enabled = False self._first_run = True self._old_data = [] # get these values under API Keys self.M2X_KEY = os.environ.get('M2X_KEY', "") # get m2x device key self.M2X_DEVICE_ID = os.environ.get('M2X_DEVICE_ID', "") # get m2x device id self.M2X_NAME = os.environ.get( 'M2X_NAME', 'DEMO_PI') # get m2x device name (default DEMO_PI) # Check if m2x push is correctly configured if len(self.M2X_KEY) != 32 or len(self.M2X_DEVICE_ID) != 32: print("M2X integration not configured, skipping") self._enabled = False return # connect to the client self._client = M2XClient(key=self.M2X_KEY) try: # create device object self._device = self._client.device(self.M2X_DEVICE_ID) except: print("M2X connection failed with the following error:") print(str(self._client.last_response.raw)) self._enabled = False return # try to load old data from disk try: with open("upload_failed_data.txt", "rb") as fp: self._old_data = pickle.load(fp) except: self._old_data = [] # DEBUG #print(self._device.data) # all good to go self._enabled = True
def main(argv): # Instantiate a client client = M2XClient(key=M2X_KEY) # Create a device #device = client.create_device( # name='Current Time Example', # description='Store current time every 10 seconds', # visibility='public' #) allfeeds = parse_all_rss_feeds() title_stream = get_stream(client, "titles") priority_stream = get_stream(client, "priority") for timestamp, priority, title, timessec in allfeeds: title_stream.add_value(title, timestamp) priority_stream.add_value(priority, timestamp) return 0
def get_from_m2x(): client = M2XClient(key='81faa53c80c0c084e797d706bc84be25') # API-KEY device = client.device('7870230c081b7f4f678dde08bc7bcba7') # DEVICE-ID # client.devices() device.stream("temperature").values(limit=6) # Get raw HTTP response raw = client.last_response.raw # Get HTTP respose status code (e.g. `200`) status = client.last_response.status # Get HTTP response headers headers = client.last_response.headers # Get json data returned in HTTP response res_json = client.last_response.json values = res_json['values'] return values
def handle(data_source_name, data_name, value): global ini try: stream_id = ini.get("stream", data_name) if stream_id is not None: client_id = ini.get("client", "key") device_id = ini.get("device", "key") if client_id is not None and client_id is not None: client = M2XClient(key=client_id) device = client.device(device_id) stream = device.stream(stream_id) print(stream.add_value(value)) if er_on: error_counter.reset_error() except requests.ConnectionError as e: error_report() if er_on: error_counter.inc_error() except: error_report() if er_on: error_counter.reset_error()
#!/usr/bin/env python import os import time from m2x.client import M2XClient client = M2XClient(key=os.environ['API_KEY']) device = client.device(os.environ['DEVICE_ID']) stream = device.stream(os.environ['stream_name']) stream_2 = device.stream(os.environ['stream_name_2']) import sys sys.path.append('/home/pi/Downloads/DHT11_Python') import RPi.GPIO as GPIO import dht11 import time import datetime # initialize GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.cleanup() # read data using pin 14 instance = dht11.DHT11(pin=4) while True: result = instance.read() if result.is_valid(): print("Last valid input: " + str(datetime.datetime.now())) print("Temperature: %d C" % result.temperature)
import requests #image processing from PIL import Image # at&t m2x from m2x.client import M2XClient #logging import logging from logging.handlers import RotatingFileHandler from ConfigParser import SafeConfigParser parser = SafeConfigParser() parser.read('config.ini') client = M2XClient(key=parser.get('m2x', 'key')) # pux m2x device = client.device(parser.get('m2x','device')) stream_recycle = device.stream('recycle') stream_garbage = device.stream('garbage') stream_trash = device.stream('trash') stream_electronics = device.stream('electonics') stream_unrecognized = device.stream('unrecognized') UPLOAD_FOLDER = '/Users/bis/att/backend' ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']) app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
from pprint import pprint import Adafruit_BMP.BMP085 as BMP from m2x.client import M2XClient ## M2X python client library sample if __name__ == '__main__': cur_dir = os.path.abspath(os.path.dirname(__file__)) os.chdir(cur_dir) with open('m2x.yml', 'r') as f: conf = yaml.load(f) api_key = conf['api_key'] device_id = conf['device_id'] stream_ids = conf['stream'] client = M2XClient(key=api_key) device = client.device(device_id) #pprint(device.data) stream_temp = device.stream(stream_ids[0]) stream_pres = device.stream(stream_ids[1]) sensor = BMP.BMP085() temp = sensor.read_temperature() pres = sensor.read_pressure() print('Temperature: %lf' % temp) print('Pressure: %lf' % pres) stream_temp.add_value(temp) print('Status: %d' % client.last_response.status) stream_pres.add_value(pres) print('Status: %d' % client.last_response.status) print(client.last_response.raw)
#! /usr/bin/env python # Run like this: # $ KEY=<YOUR APIKEY> DEVICE=<YOUR DEVICE ID> python export_values.py import sys, os, time sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from m2x.client import M2XClient KEY = os.environ["KEY"] DEVICE = os.environ["DEVICE"] client = M2XClient(key=KEY) device = client.device(DEVICE) res = device.values_export() location = res.headers["location"] print "The job location is in %s" % location job = client.job(location.split("/")[-1]) state = job.state while state != "complete": if state == "failed": sys.exit("Job has failed to complete")
import os import datetime from models import StreamParser, FlowStream from m2x.client import M2XClient from flask import Flask, render_template app = Flask(__name__) app.config.from_pyfile('config.py') client = M2XClient(os.environ['MASTER_API_KEY']) device = client.device(os.environ['DEVICE_ID']) @app.route('/') def main(): temp_stream = StreamParser(device.stream('temperature')) flow_stream = FlowStream(device.stream('water_use')) return render_template('body.html', temp_stream=temp_stream, flow_stream=flow_stream)
def setup_class(self): self.client = M2XClient(key=TEST_KEY, api=APIBase) self.api = self.client.api
from m2x.client import M2XClient F = open("/home/pi/mx.2", "r") mac_address = F.readline().replace('\n', '') mac_address = mac_address.replace('\r', '') m2x_key = F.readline().replace('\n', '') m2x_key = m2x_key.replace('\r', '') m2x_device = F.readline().replace('\n', '') m2x_device = m2x_device.replace('\r', '') stream1 = F.readline().replace('\n', '') stream1 = stream1.replace('\r', '') stream2 = F.readline().replace('\n', '') stream2 = stream2.replace('\r', '') F.close() client = M2XClient(key=m2x_key) device = client.device(m2x_device) # Create a data stream associated with target Device streamTemp = device.stream(stream1) streamBat = device.stream(stream2) if os.getenv('C', '1') == '0': ANSI_RED = '' ANSI_GREEN = '' ANSI_YELLOW = '' ANSI_CYAN = '' ANSI_WHITE = '' ANSI_OFF = '' else: ANSI_CSI = "\033["
import os import time import datetime import Adafruit_BluefruitLE from m2x.client import M2XClient from Adafruit_BluefruitLE.services import UART # m2x info DEVICE_ID = ### PRIMARY_API_KEY = ### # instantiate a client client = M2XClient(key=PRIMARY_API_KEY) # use our device device = client.device(DEVICE_ID) # use the temperature stream stream = device.stream('temperature') # create our bluetooth LE reader ble = Adafruit_BluefruitLE.get_provider() def main(): ble.clear_cached_data() # get bluetooth adapter and turn it on adapter = ble.get_default_adapter() adapter.power_on()
def setup_class(self): self.client = M2XClient(key=self.TEST_KEY, api=APIVersion2) self.api = self.client.api
else: logging.basicConfig(level=default_level) # Load logging configuration setup_logging() logger = logging.getLogger('pyfi') # Get M2X Master API Key from keys.txt with open('keys.txt', 'r') as f: APIKEY = f.readline().strip() DEVICE_NAME = 'rpi-network-monitor' CLIENT = M2XClient(key=APIKEY) # M2X has both numeric and non-numeric streams # In this case the mac addresses will be stored as json non_numeric_stream = 'mac_addresses' numeric_streams = [ 'number_mac_addresses', 'total_connections', 'number_unknown_connections' ] scanner = Scanner() controller = Controller(CLIENT, DEVICE_NAME, non_numeric_stream, *numeric_streams) if __name__ == "__main__":
import RPi.GPIO as GPIO import os print('xxx') print('xxe3x') # interval LOOP_INTERVAL = 10 API_KEY = 'aa62d842819f547e4213edd1b9a19e92' DEVICE_ID = 'df834a7986e9a52d5d28e46dd97e87df' try: from m2x.client import M2XClient client = M2XClient(API_KEY) device = client.device(DEVICE_ID) #device = client.create_device( # name='currenttime', # description='Store current time ', # visibility= 'public' #) temp_stream = device.stream('temperture') humidity_stream = device.stream('humidit') #set up GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(10, GPIO.OUT) except: print('exception!') # Get I2C bus
Scroll_SSD1306.addLineOLED(display, (" Welcome to ")) Scroll_SSD1306.addLineOLED(display, (" Smart Garden ")) ############ # Setup Moisture Pin for GrovePowerSave ############ GPIO.setup(config.moisturePower, GPIO.OUT) GPIO.output(config.moisturePower, GPIO.LOW) # try: # Creating M2X Client and device client = M2XClient(key='3e296370312002710e5019d6b4a4b512') device = client.device('cb3eed668dcb1cdf4e3b42df2c4fa00e') temperature_stream = device.streams()[0] humidity_stream = device.streams()[1] visible_light_strean = device.streams()[2] ir_light_strean = device.streams()[3] uv_light_stream = device.streams()[4] soil_moisture_stream = device.streams()[5] water_tank_stream = device.streams()[6] # read temp humidity degrees = hdc1000.readTemperature() humidity = hdc1000.readHumidity() print 'Temp = {0:0.3f} deg C'.format(degrees)
#!/usr/bin/env python import os import glob import time from datetime import datetime #from EmulatorGUI import GPIO import RPi.GPIO as GPIO from sensors import FlowMeter, OneWireTempSensor #from secrets import MASTER_API_KEY, DEVICE_ID from m2x.client import M2XClient from m2x.utils import to_iso # Initialize M2X Client, change MASTER_API_KEY and DEVICE_ID to yours client = M2XClient('1a091c4edb7cdb41004de52ee2d5f61b') device = client.device('ca09937cf8f45cebd27e6c80694217d6') temp_stream = device.stream('temperature') flow_stream = device.stream('water_use') # Set up GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_UP) # With only one temp sensor connected first sensor name in the list is # all you need, with more you need to figure out which one you want to use sensor_names = OneWireTempSensor.find_temp_sensors() # Initialize One Wire Temp Sensor tempsensor = OneWireTempSensor(sensor_names[0]) # initialize flow meter
# data graph look more interesting. import time from m2x.client import M2XClient API_KEY = "b2762079a8b9115e0f11060b5d73098a" # Replace this value with the Master API Key for your M2X account DEVICE = 'Example_07' STREAM = 'time_values' my_device = "" my_stream = "" sign = 1 base_time = int(time.time()) print("\nLooking for device '" + DEVICE + "' with stream '" + STREAM + "'.") client = M2XClient(key=API_KEY) # Get M2X client # Find or create the device devices = client.devices() # Get list of devices for device in devices: # Look for DEVICE in list of devices if device.name == DEVICE: my_device = device print("Found device: " + str(my_device.name)) if my_device == "": # Did we find the DEVICE? print("Creating device: " + DEVICE) my_device = client.create_device( # If not, create the DEVICE name=DEVICE, description='Store current time every 10 seconds for a minute', visibility='public') print("Created device_id: " + str(my_device.id))
def checkTemp(sc): # interval in sec production value should be 10 LOOP_INTERVAL=1 #API_KEY = 'aa62d842819f547e4213edd1b9a19e92' #PRODUCTION API_KEY = '06ed89baf1866d4aeac7f21b84e51636' #TEST ENV #DEVICE_ID = 'df834a7986e9a52d5d28e46dd97e87df' #PRODUCTION DEVICE_ID = 'bbdbe6fd59dfcebbe34727321b61b565' #TEST ENV count=0 templist = [] try: from m2x.client import M2XClient client = M2XClient(API_KEY) device = client.device(DEVICE_ID) GPIO.setmode(GPIO.BCM) GPIO.setup(10, GPIO.OUT) temp_stream = device.stream('temperture') humidity_stream = device.stream('humidit') #device = client.create_device( # name='currenttime', # description='Store current time ', # visibility= 'public' #) #set up GPIO # Get I2C bus ##bus = smbus.SMBus(1) #turn the LED on GPIO.output(10,1) # HDC1000 address, 0x40(64) # Select configuration register, 0x02(02) # 0x30(48) Temperature, Humidity enabled, Resolultion = 14-bits, Heater on #bus.write_byte_data(0x40, 0x02, 0x30) # HDC1000 address, 0x40(64) # Send temp measurement command, 0x00(00) #bus.write_byte(0x40, 0x00) ##time.sleep(0.1) # HDC1000 address, 0x40(64) # Read data back, 2 bytes # temp MSB, temp LSB data0 = 11#bus.read_byte(0x40) data1 = 12#bus.read_byte(0x40) # Convert the data temp = (data0 * 256) + data1 cTemp = (temp / 65536.0) * 165.0 - 40 cTemp = round(cTemp,2) fTemp = cTemp * 1.8 + 32 # HDC1000 address, 0x40(64) # Send humidity measurement command, 0x01(01) #bus.write_byte(0x40, 0x01) #turn the LED off GPIO.output(10,0) ##time.sleep(0.1) # HDC1000 address, 0x40(64) # Read data back, 2 bytes # humidity MSB, humidity LSB data0 = 3#bus.read_byte(0x40) data1 = 5#bus.read_byte(0x40) # Convert the data humidity = (data0 * 256) + data1 humidity = (humidity / 65536.0) * 100.0 # Output data to screen #print (time.ctime()) logger.debug ("Relative Humidity : %.2f %%" %humidity) logger.debug ("Temperature in Celsius : %.2f C" %cTemp) # print "Temperature in Fahrenheit : %.2f F" %fTemp count+=1 # send a message if count surpase LOOP_INTERVAL if (count ) >= LOOP_INTERVAL: #turn the LED on GPIO.output(10,1) logger.info('---sending data to m2x....---') #send data to m2x humidity_stream.add_value(humidity) temp_stream.add_value(cTemp) #reset count count=0 # except ConnectionError: # GPIO.cleanup() # logger.warning('connection error! program will sleep for 5 sec before restart') # time.sleep(5) except Exception: logger.error(sys.exc_info()) pass finally: logger.info("finally.") s.enter(2, 1, checkTemp, (sc,))
#!/usr/bin/env python import os import glob import time from datetime import datetime import RPi.GPIO as GPIO from sensors import FlowMeter, OneWireTempSensor #from secrets import MASTER_API_KEY, DEVICE_ID from m2x.client import M2XClient from m2x.utils import to_iso # Initialize M2X Client, change MASTER_API_KEY and DEVICE_ID to yours client = M2XClient(MASTER_API_KEY) device = client.device(DEVICE_ID) temp_stream = device.stream('temperature') flow_stream = device.stream('water_use') # Set up GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_UP) # With only one temp sensor connected first sensor name in the list is # all you need, with more you need to figure out which one you want to use sensor_names = OneWireTempSensor.find_temp_sensors() # Initialize One Wire Temp Sensor tempsensor = OneWireTempSensor(sensor_names[0]) # initialize flow meter flowmeter = FlowMeter(tempsensor)