def __init__(self, dev): Peripheral.__init__(self) Thread.__init__(self) self.setDaemon(True) self.dev = dev self.isConnected = False self.am = ambient.Ambient(channelID, writeKey)
def loop(): tmp = 0.0 while True: datetime_dat = datetime.now() time_str = datetime_dat.strftime('%Y/%m/%d') tmp = ds18b20.ds18b20Read() segment.numberDisplay_dec(tmp) print("Publishing message: %s to topic: %s" % (tmp, Topic)) client.publish(Topic, tmp) am = ambient.Ambient(channelID, writeKey) r = am.send({'d1': tmp}) dateappend = datetime_dat temperature = tmp cnn = mysql.connector.connect(host='yourmysqlhost', port=mysqlport, db='yourdbname', user='******', passwd='yourpasswd', charset="utf8") cur = cnn.cursor() cur.execute("""INSERT INTO yoursensortablename (DateAppend, Temperature) VALUES (%s, %s)""", (dateappend, temperature)) cnn.commit() time.sleep(60)
def setup_ambient(self): """Ambientサーバーへの通信オブジェクトのセットアップを行う """ param = self.get_ambient_parameter() print("ambient setup_ambient {}".format(param)) if not (param["write_key"] == 0 and param["channelId"] == 0): self.ambient = ambient.Ambient(param["channelId"], param["write_key"]) else: print("Ambient Parameter Not found")
def testfunc(info, datainfo, r): am = ambient.Ambient(info['CHID'], info['WRITE_KEY'], info['READ_KEY'], info['USER_KEY']) print('{0}'.format(r)) try: res = am.send({'d1':r[0], 'd2':r[1]}) print(res) d = am.read(n=datainfo['res']) print(d) except requests.exceptions.RequestException as e: print('request failed: ', e)
def SendToAmbient(data, device): senddata = {'created': data['Date'], 'd1': data['Temperature']} if 'Humidity' in data: senddata['d2'] = data['Humidity'] print(f'senddata:{str(senddata)}') am = ambient.Ambient(device.API_URL, device.Token) try: ret = am.send(senddata) print('sent to Ambient (ret = %d)' % ret.status_code) logging.info('sent to Ambient (ret = %d)' % ret.status_code) except requests.exceptions.RequestException as e: print('Ambient.send request failed: ', e) logging.error(f'Ambient.send request failed:{str(e)}')
def post(): post_data = request.get_data().splitlines() post_data = list(map(lambda x: int(x), post_data)) ijid = post_data[0] calib = post_data[1:1 + 32] data = post_data[1 + 32:1 + 32 + 8] bme280 = BME280() bme280.setCalib(calib) bme280.setData(data) app.logger.info("T: %0.2f, P: %0.2f, H: %0.2f" % (bme280.T, bme280.P, bme280.H)) db_insert2(ijid, bme280.T, bme280.P, bme280.H) am = ambient.Ambient(os.environ['AM_CHANNEL'], os.environ['AM_WRITE_KEY']) am.send({'d1': bme280.T, 'd2': bme280.P, 'd3': bme280.H}) return 'ok'
def bme280(): post_data = request.get_data().splitlines() channel = post_data[0].decode('utf-8').strip() writekey = post_data[1].decode('utf-8').strip() post_data = list(map(lambda x: int(x), post_data[2:])) calib = post_data[0:32] data = post_data[32:32 + 8] bm = BME280() bm.setCalib(calib) bm.setData(data) app.logger.info("channel: %s, T: %0.2f, P: %0.2f, H: %0.2f" % (channel, bm.T, bm.P, bm.H)) db_insert(channel, bm.T, bm.P, bm.H) am = ambient.Ambient(channel, writekey) am.send({'d1': bm.T, 'd2': bm.P, 'd3': bm.H}) return 'ok'
def main(): am = ambient.Ambient(channelId, '', readKey) data = am.read(n=1) temp = data[0]['d1'] humid = data[0]['d2'] created = data[0]['created'] level = WBGTlevel(humid, temp) print({'temp': temp, 'humid': humid, 'level': level, 'created': created}) if (level > 1 or debug): requests.post(IFTTT_URL + IFTTT_KEY, json={ 'value1': temp, 'value2': humid, 'value3': WBGTmsg[level] })
def __init__(self): ''' Ambientに接続するためのキーが環境変数にセットされているかの確認 該当する環境変数がない場合は強制終了 ''' try: CHANNEL_ID = int(os.environ['AMBIENT_CHANNEL_ID']) WRITE_KEY = os.environ['AMBIENT_WRITE_KEY'] except KeyError: print(KeyError) exit(1) # Ambientインスタンスの作成 self.am = ambient.Ambient(CHANNEL_ID, WRITE_KEY) # バッファー用のデータを初期化 self.datas = [] # 最終送信時刻 self.last_posted_at = datetime.now()
def am_thread(): global S_CO2HAT, S_ENV2 global am_interval global Am_err global AM_CID, AM_UID global AM_WKEY, AM_RKEY global co2, mhztemp global temp, hum, pres if (AM_CID is not None) and (AM_WKEY is not None) and (S_CO2HAT or S_ENV2) : # Ambient設定情報があった場合 / どちらかのセンサがあった場合 import ambient am_co2 = ambient.Ambient(AM_CID, AM_WKEY) print("ambient thread start") data = {} am_tc = 0 Am_err = 1 while True: if (utime.time() - am_tc) >= am_interval : # インターバル値の間隔でAmbientへsendする data.clear() if (co2 is not None) : data["d1"] = co2 if (mhztemp is not None) : data["d2"] = mhztemp if (temp is not None) : data["d3"] = temp if (hum is not None) : data["d4"] = hum if (pres is not None) : data["d5"] = pres if len(data) > 0 : try : r = am_co2.send(data) print('Ambient send OK! / ' + str(r.status_code) + ' / ' + str(Am_err)) Am_err = 0 r.close() except: print('Ambient send ERR! / ' + str(Am_err)) Am_err += 1 am_tc = utime.time() utime.sleep(1)
def main(): ambient_channel_id = os.environ["AMBIENT_CHANNEL_ID"] ambient_write_key = os.environ["AMBIENT_WRITE_KEY"] command = "speedtest -s 15047 -f json" proc = subprocess.run( command, shell=True, stdout=PIPE, stderr=PIPE, text=True, ) result = json.loads(proc.stdout) am = ambient.Ambient(ambient_channel_id, ambient_write_key) am.send({ "d1": result["download"]["bandwidth"] / (1000**2 / 8), "d2": result["upload"]["bandwidth"] / (1000**2 / 8), })
def handleDiscovery(self, dev, isNewDev, isNewData): if isNewDev or isNewData: for (adtype, desc, value) in dev.getScanData(): #print(adtype, desc, value, dev.addr) if desc == 'Manufacturer' and value[0:4] == 'ffff': if dev.addr not in devices: return if dev.addr not in self.devs: amconf = devices[dev.addr] self.devs[dev.addr] = { 'lastseq': None, 'lasttime': datetime.fromtimestamp(0), 'ambient': ambient.Ambient(amconf['channelID'], amconf['writeKey']), } delta = datetime.now() - self.devs[dev.addr]['lasttime'] if value[4:6] != self.devs[dev.addr]['lastseq'] and delta.total_seconds() > 11: # アドバタイズする10秒の間に測定が実行されseqが加算されたものは捨てる self.devs[dev.addr]['lastseq'] = value[4:6] self.devs[dev.addr]['lasttime'] = datetime.now() send2ambient(dev.addr, self.devs[dev.addr]['ambient'], value[6:])
def _sendambient(self, sensorval): data = {} data['d1'] = sensorval['IRtemperature'][0] data['d2'] = sensorval['humidity'][1] data['d3'] = sensorval['barometer'][1] data['d5'] = sensorval['lightmeter'] data['d4'] = sensorval['battery'] if not self.am: d = self.r.hgetall(self.addr) dd = dict([(k.decode('utf-8'), v.decode('utf-8')) for k, v in d.items()]) ch = dd.get('ch', '') if ch == 'None': ch = '' writekey = dd.get('writekey', '') if writekey == 'None': writekey = '' if ch != '' and writekey != '': self.am = ambient.Ambient(ch, writekey) MSG('send to Ambient ', dt.now().strftime("%Y/%m/%d %H:%M:%S"), ' for ', self.addr) MSG(data) if self.am: ret = self.am.send(data) MSG('sent to Ambient (ret: %d)' % ret.status_code, ' for ', self.addr) sys.stdout.flush()
def sent_Ambient(amDATA, sendDATA): # create Ambient Object am = ambient.Ambient(amDATA['channelID'], amDATA['WriteKEY']) #データの作成 dictionaryで作成する #データはd1~d8として作成する。 #ローカルタイムスタンプは 'created': 'YYYY-MM-DD HH:mm:ss.sss' として作成する。 for retry in range(6): # 10秒間隔で6回リトライ try: ret = am.send(sendDATA) logging.info("sent to Ambient (ret = {0})".format(ret.status_code)) return True except requests.exceptions.RequestException as e: logging.error("[Ambient] request failed : {0}".format(e)) time.sleep(10) except Exception as e: logging.error("[Ambient] Exception : {0}".format(e)) return False
# WiFi設定 wifiCfg.autoConnect(lcdShow=True) wifiCfg.network.WLAN(wifiCfg.network.AP_IF).active(False) lcd.clear() lcd.print('*', 0, 0, lcd.WHITE) print('>> WiFi init OK') # UDPデータインスタンス生成 u = wisun_udp.udp_read() print('>> UDP reader init OK') # Ambientインスタンス生成 if (AM_ID_1 is not None) and (AM_WKEY_1 is not None): # Ambient_1の設定情報があった場合 import ambient am_now_power = ambient.Ambient(AM_ID_1, AM_WKEY_1) print('>> Ambient_1 init OK') if (AM_ID_2 is not None) and (AM_WKEY_2 is not None): # Ambient_2の設定情報があった場合 import ambient am_total_power = ambient.Ambient(AM_ID_2, AM_WKEY_2) print('>> Ambient_2 init OK') lcd.print('**', 0, 0, lcd.WHITE) # BP35C0-J11 UART設定 uart = machine.UART(1, tx=0, rx=36) # Wi-SUN HAT rev0.1用 #uart = machine.UART(1, tx=0, rx=26) uart.init(115200, bits=8, parity=None, stop=1, timeout=50) lcd.print('***', 0, 0, lcd.WHITE) print('>> UART init OK') buf = J11Read(uart)
if __name__ == '__main__': #added begin try: CHANNEL_ID = int(os.environ['AMBIENT_CHANNEL_ID']) WRITE_KEY = os.environ['AMBIENT_WRITE_KEY'] except KeyError as e: print('Missing environment variable: '.format(e)) exit(1) # EnvSensorクラスの実体を作成します e = EnvSensor() # スレッドとして処理を開始します e.start() am = ambient.Ambient(CHANNEL_ID, WRITE_KEY) last_uploaded = datetime.now() while True: try: timestamp = datetime.now() if (timestamp - last_uploaded).seconds > 10: am.send({ "d1": e.get_co2(), "created": timestamp.strftime("%Y/%m/%d %H:%M:%S") }) time.sleep(5) # CO2データを取得し、print関数で表示します print("eCO2: {}".format(e.get_co2())) print("eTEMP: {}".format(e.get_temp())) except KeyboardInterrupt:
import datetime AMBIENT_CHANNEL_ID = int(os.environ['AMBIENT_CHANNEL_ID']) AMBIENT_WRITE_KEY = os.environ['AMBIENT_WRITE_KEY'] CHECK_SPAN = int(os.environ.get('CHECK_SPAN', '30')) BLUETOOTH_DEVICEID = os.environ.get('BLUETOOTH_DEVICEID', 0) BLUETOOTH_DEVICE_ADDRESS = os.environ.get('BLUETOOTH_DEVICE_ADDRESS', None) if BLUETOOTH_DEVICE_ADDRESS is None: sys.exit('No sensors found') o = EnvStatus(bt=BLUETOOTH_DEVICEID) uId = o.setRequest(BLUETOOTH_DEVICE_ADDRESS) o.start() am = ambient.Ambient(AMBIENT_CHANNEL_ID, AMBIENT_WRITE_KEY) latest_update = datetime.datetime.now() while True: data = o.getLatestData(uId) if data is not None: if data.tick_last_update > latest_update: am.send({ 'created': data.tick_last_update.strftime('%Y-%m-%d %H:%M:%S'), 'd1': data.val_temp, 'd2': data.val_light })
def do_connect(ssid, password): import network sta_if = network.WLAN(network.STA_IF) if not sta_if.isconnected(): print('connecting to network...') sta_if.active(True) sta_if.connect(ssid, password) while not sta_if.isconnected(): pass print('network config:', sta_if.ifconfig()) i2c = I2C(scl=Pin(4), sda=Pin(5)) bme = bme280.BME280(i2c=i2c) am = ambient.Ambient(channelId, writeKey) do_connect(ssid, password) while True: data = bme.read_compensated_data() print(bme.values) r = am.send({ 'd1': data[0] / 100.0, 'd2': data[2] / 1024.0, 'd3': data[1] / 25600.0 }) print(r.status_code) r.close() utime.sleep(30)
import io_data import sensors import dashboard import resources import ambient import random import socket from tendo import singleton from utils import log_stderr, os_async_command io_status = io_data.Status() sensor = sensors.Sensors() lcd = dashboard.Dashboard() ambient = ambient.Ambient() TEST_INIT_TEMP = 20.0 TEST_DELTA_EXT_INT_COEFF = .001 TEST_DELTA_THERMO_ON_TEMP_C = .03 current_status = '' sig_command = False is_status_changed = True initial_time = datetime.datetime.now() sig_switch_timeout = [datetime.datetime.now()]*len(config.BUTTONS) temp = temp_avg_accu = temp_avg_sum = 0.0 temp_avg_counter = 0 log_temp_avg_accu = log_temp_avg_sum = 0.0 log_temp_avg_counter = 0
import ambient # Ambientライブラリをインポート essid = 'ssid' password = '******' channelId = 100 writeKey = 'writeKey' def do_connect(): # Wi-Fiネットワークに接続 import network wlan = network.WLAN(network.STA_IF) wlan.active(True) if not wlan.isconnected(): print('connecting to network...') wlan.connect(essid, password) while not wlan.isconnected(): pass print('network config:', wlan.ifconfig()) i2c = I2C(scl = Pin(22), sda = Pin(21)) # I2Cオブジェクトを作る si7021 = si7021.SI7021(i2c) # SI7021オブジェクトを作る do_connect() am = ambient.Ambient(channelId, writeKey) # チャネルIDとライトキーを指定してAmbientオブジェクトを作る temp = si7021.temp # Si7021から温度を取得 ----② humid = si7021.humid # 湿度を取得 print(temp, humid) r = am.send({'d1': temp, 'd2': humid}) # 温度、湿度をAmbientに送信 print('status code:', r.status_code) # 送信のステータスコードをプリント machine.deepsleep(SLEEP_TIME * 1000 - (time.ticks_ms() - start)) # Deep sleepする ----③
myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec # Wait for network connection while True: try: # Connect and subscribe to AWS IoT myAWSIoTMQTTClient.connect() if args.mode == 'both' or args.mode == 'subscribe': myAWSIoTMQTTClient.subscribe(topic, 1, customCallback) time.sleep(2) break except Exception as e: print(e) # Initialize Ambient am = ambient.Ambient(ambientChannelId, ambientWriteKey) # Publish to the same topic in a loop forever while True: if args.mode == 'both' or args.mode == 'publish': # Get fan speed fanSpeed = subprocess.check_output( ['cat', '/sys/devices/pwm-fan/target_pwm']).decode('utf-8').rstrip('\n') fanSpeed = 100 * int(fanSpeed) / 255 # Get temperature zone_paths = thermal_zone.get_thermal_zone_paths() zone_names = thermal_zone.get_thermal_zone_names(zone_paths) zone_temps = thermal_zone.get_thermal_zone_temps(zone_paths) # Convert to celsius
# -*- coding: utf-8 -*- #!/usr/bin/python import RPi.GPIO as GPIO import os import smbus import time import datetime import ambient #Input your ambients ID or writeKey ambi = ambient.Ambient(ID, 'writeKey') # ADXL345 Class class ADXL345(): DevAdr = 0x53 myBus = "" if GPIO.RPI_INFO['P1_REVISION'] == 1: myBus = 0 else: myBus = 1 b = smbus.SMBus(myBus) def setUp(self): self.b.write_byte_data(self.DevAdr, 0x2C, 0x0B) # BandwidthRate self.b.write_byte_data(self.DevAdr, 0x31, 0x00) # DATA_FORMAT 10bit 2g self.b.write_byte_data(self.DevAdr, 0x38, 0x00) # FIFO_CTL OFF self.b.write_byte_data(self.DevAdr, 0x2D, 0x08) # POWER_CTL Enable def getValueX(self):
# -*- coding: utf-8 -*- import ambient import bme280_sample import weathernewsdata import webpressdata chID = 25204 #Channel ID specified by Ambient wkey = 'xxxxxxxxxxxxxxxx' #your user key am = ambient.Ambient(chID, wkey) # センサー計測データ読み込み sensdata = bme280_sample.readData() bme_t = sensdata[0] bme_p = sensdata[1] bme_h = sensdata[2] #気象ウェブページからスクレイピング webdata = weathernewsdata.readData() web_t = webdata[0] web_h = webdata[1] # 気象ウェブページからスクレイピング web_p = webpressdata.readData() r = am.send({ 'd1': bme_t, 'd2': bme_p, 'd3': bme_h, 'd4': web_t, 'd5': web_p,
import ambient 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=14) ambi = ambient.Ambient("<channelID>", "<apikey>") while True: result = instance.read() if result.is_valid(): json = {} # print("Last valid input: " + str(datetime.datetime.now())) # print("Temperature: %d C" % result.temperature) # print("Humidity: %d %%" % result.humidity) json["d1"] = result.temperature json["d2"] = result.humidity print(json) try: ambi.send(json) except Exception: pass time.sleep(300)
import RPi.GPIO as GPIO import dht11 import time import datetime import ambient # ご自分のチャネルID、ライトキーに置き換えてください ambi = ambient.Ambient(2607, "fca0d37c61f9dc95") # 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) print("Humidity: %d %%" % result.humidity) r = ambi.send({"d3": result.temperature, "d4": result.humidity}) time.sleep(10)
#!/usr/bin/python3 import RPi.GPIO as GPIO import dht11 import time import datetime import ambient import os # initialize GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.cleanup() # read data using pin 14 instance = dht11.DHT11(pin=14) while True: result = instance.read() if result.is_valid(): with open('dht11_example.log', 'a', encoding='utf-8') as f: f.write('{},Temp:{},Humid:{}\n'.format(datetime.datetime.now(), result.temperature, result.humidity)) ambi = ambient.Ambient(os.environ["AMBIENT_ID"], os.environ["AMBIENT_WTOKEN"]) r = ambi.send({"d1": result.temperature, "d2": result.humidity}) break time.sleep(1)
def main(): channelId = チャネルID writeKey = 'ライトキー' parser = argparse.ArgumentParser() parser.add_argument('-i', action='store', type=float, default=120.0, help='scan interval') parser.add_argument('-t', action='store', type=float, default=5.0, help='scan time out') arg = parser.parse_args(sys.argv[1:]) scanner = bluepy.btle.Scanner(0) am = ambient.Ambient(channelId, writeKey) while True: dev = None print('scanning tag...') devices = scanner.scan(arg.t) # BLEをスキャンする for d in devices: for (sdid, desc, val) in d.getScanData(): if sdid == 9 and val == 'CC2650 SensorTag': # ローカルネームが'CC2650 SensorTag'のものを探す dev = d print('found SensorTag, addr = %s' % dev.addr) sys.stdout.flush() if dev is not None: tag = bluepy.sensortag.SensorTag(dev.addr) # 見つけたデバイスに接続する tag.IRtemperature.enable() tag.humidity.enable() tag.barometer.enable() tag.battery.enable() tag.lightmeter.enable() # Some sensors (e.g., temperature, accelerometer) need some time for initialization. # Not waiting here after enabling a sensor, the first read value might be empty or incorrect. time.sleep(1.0) data = {} data['d1'] = tag.IRtemperature.read()[ 0] # set ambient temperature to d1 data['d2'] = tag.humidity.read()[1] # set humidity to d2 data['d3'] = tag.barometer.read()[1] # set barometer to d3 data['d5'] = tag.lightmeter.read() # set light to d5 data['d4'] = tag.battery.read() # set battery level to d4 tag.IRtemperature.disable() tag.humidity.disable() tag.barometer.disable() tag.battery.disable() tag.lightmeter.disable() print(data) r = am.send(data) print(r.status_code) sys.stdout.flush() time.sleep(arg.i) # tag.waitForNotifications(arg.t) tag.disconnect() del tag
def MSG(*args): if Verbose: msg = " ".join([str(a) for a in args]) print(msg) sys.stdout.flush() def sendWithRetry(am, data): for retry in range(6): try: ret = am.send(data) MSG('sent to Ambient (ret = %d)' % ret.status_code) break except requests.exceptions.RequestException as e: MSG('request failed.') time.sleep(10) am = ambient.Ambient(int(CHANNEL), WRITEKEY) sensor = DHT11(DHT11_PIN) while True: try: data = sensor.read(retries=5) except TimeoutError: data = {"valid": False} if data["valid"]: MSG("temperature: {} / humidity: {}".format(data["temp_c"], data["humidity"])) sendWithRetry(am, {'d1': data["temp_c"], 'd2': data["humidity"]}) time.sleep(180)
if a != None: lcd.print(a, 40, y) if b != None: lcd.print(b, 135, y) if c != None: lcd.print(c, 225, y) def dispTHP(t, h, p): _, y = lcd.fontSize() lcd.print("%.1f" % t + "'C", lcd.CENTER, 10) lcd.print("%.1f" % h + "%", lcd.CENTER, 20 + y) lcd.print("%.1f" % p + "hPa", lcd.CENTER, 30 + y * 2) pir = PIR(handler=cb) # callback関数を指定してPIRのインスタンスを作る env = units.ENV() # ENVセンサーのインスタンスを作る am = ambient.Ambient(100, 'writeKey') # Ambientのインスタンスを作る print('start') lcd.clear() # LCDを消去する lcd.setBrightness(0 if dark else 80) lcd.font(lcd.FONT_Default) menu('stop', '', 'disp on/off') # ボタンAの上に'stop'を書く lcd.font(lcd.FONT_DejaVu24) while True: startT = time.time() end = False state = machine.disable_irq() n = nmoves nmoves = 0 machine.enable_irq(state)
import machine import network import bme280 import ambient import esp ssid = "ess-id" password = "******" i2c = machine.I2C(scl=machine.Pin(5), sda=machine.Pin(4)) if (i2c.scan()[0] == 0x76): bme = bme280.BME280(i2c=i2c) am = ambient.Ambient(ch - id, 'write-key') station = network.WLAN(network.STA_IF) station.active(True) station.connect(ssid, password) while station.isconnected() == False: pass print(station.ifconfig()) print(bme.values) data = bme.read_compensated_data() r = am.send({ 'd1': data[0] / 100.0, 'd2': data[2] / 1024.0, 'd3': data[1] / 25600.0 }) print(r.status_code) r.close() esp.deepsleep(600 * 1000000)