Example #1
0
    def pushSensorDataCloudChannels(self, enCoSensor,  debug = False,  forceCreateChannel = False):
        data = enCoSensor.getAsJson()
        self._getToken(debug)
        
        if not self.sensorHasCCDefinition(enCoSensor, debug):
            if debug: print("-- Sensor has NO CC-IN stream definition.")
            self._createCCInStreamDefinition(enCoSensor, debug)
        else:
            if forceCreateChannel:
                self._createCCInStreamDefinition(enCoSensor, debug)
                if debug: print("-- Sensor HAD CC-IN stream definition! BUT RECREATED !!")
            else:
                if debug: print("-- Sensor HAS CC-IN stream definition!")
        
        postUrl = "{}/cc/u/{}".format(self.connectToURLforCC_In, enCoSensor.getCloudChannelCustomHTTP())
        
        if debug: 
            print('Sending endpoint : ', postUrl)
            print('Payload : ',  data)
                
        auth_header = {'Authorization':'Bearer {}\r\n'.format(self.tokenBearer), 'Accept':'application/json'}
        
        #TODO : investigate why binary path causes 500 error, send as JSON seems to work ....
        resp = http_client.post(postUrl, headers=auth_header, json=data, debug = debug)

#        if enCoSensor.sendAsBinary() != True:
#            resp = http_client.post(postUrl, headers=auth_header, json=data, debug = debug)
#        else:
#            resp = http_client.post(postUrl, headers=auth_header, binary=data, debug = debug)
            
        if debug: print (resp.getStatus())
        resp.raise_for_status()
        resp.close()
Example #2
0
    def _getToken(self, debug = False):
        if self.apiKey == None or self.apiSecret == None or self.userName == None :
            raise OSError('Missing authentication info!')
            
        if self.validUntil == None or time() >= self.validUntil:
            basic_auth = ubinascii.b2a_base64("{}:{}".format(self.apiKey, self.apiSecret)).decode('ascii')
            auth_header = {'Authorization':'Basic {}'.format(basic_auth), 'Accept':'application/json'}

            body = 'grant_type=client_credentials&scope=openid'
            if debug: print(self.connectToURLforToken)
            resp = http_client.post(self.connectToURLforToken, headers=auth_header, textMsg=body, contentType='application/x-www-form-urlencoded',  debug = debug)
            resp.raise_for_status()
            resp.content
            if debug:
                print ('Response : ')
                print (resp.content)
            
            authInfo = resp.json()
            self.tokenBearer = authInfo['access_token']
            
            try:
                self.validUntil = time() + authInfo['expires_in']
                localtime(self.validUntil)
            except OverflowError:
                if debug:
                    print("Permanent token, setting to 1 week validity")
                self.validUntil = time() + 7 * 24 * 60 * 60

            resp.close()
            if debug: print ("Token retrieved ! valid until {}".format(localtime(self.validUntil)))
        else:
            if debug: print ("Token still valid !  Re-using it ! {}".format(self.tokenBearer))
Example #3
0
 def create_hit(self,
                type,
                title,
                description,
                attachment_id,
                campaign_id,
                credit,
                required_answer_count,
                location_id=1,
                min_selection_count=1,
                max_selection_count=1,
                begin_time=1,
                end_time=1):
     response = post(self.api_host + 'rest/hit',
                     json={
                         'type': type,
                         'title': title,
                         'description': description,
                         'attachment_id': attachment_id,
                         'campaign_id': campaign_id,
                         'credit': credit,
                         'required_answer_count': required_answer_count,
                         'location_id': location_id,
                         'requester_id': self.user['id'],
                         'min_selection_count': min_selection_count,
                         'max_selection_count': max_selection_count,
                         'begin_time': begin_time,
                         'end_time': end_time
                     },
                     token=self.token)
     if response:
         # print 'HIT created', response.get('id', 0)
         return response
 def create_selection(self, hit_id, brief):
     response = post(self.api_host + 'rest/selection',
                     json={'hit_id': hit_id, 'brief': brief},
                     token=self.token)
     if response:
         print 'Selection created', response.get('id', 0)
         return response.get('id', 0)
 def user_auth(self, username, password):
     response = post(self.api_host + 'user/auth', json={'username': username, 'password': password},
                     token=self.token)
     if 'token' in response:
         self.token = response['token']
         self.user = response
         print 'User auth token', self.token
 def assign_user_to_campaign(self, campaign_id, role_id=2):
     response = post(self.api_host + 'rest/campaign_user',
                     json={'user_id': self.user['id'], 'campaign_id': campaign_id, 'role_id': role_id},
                     token=self.token)
     if 'id' in response:
         print 'Assigned user(%d) to campaign(%d)'%(self.user['id'], campaign_id)
         return response
 def create_answer(self, hit_id, brief, attachment_id, type, location_id):
     response = post(self.api_host + 'rest/answer',
                     json={'type': type, 'brief': brief, 'attachment_id': attachment_id, 'hit_id': hit_id,
                           'location_id': location_id, 'worker_id': self.user['id']}, token=self.token)
     if response:
         print 'Answer created', response.get('id', 0)
         return response
 def create_location(self, name, longitude, latitude, altitude=0.0):
     response = post(self.api_host + 'rest/location', json={'name': name, 'coordinate': {'longitude': longitude,
                                                                                         'latitude': latitude,
                                                                                         'altitude': altitude}},
                     token=self.token)
     if response:
         print 'Location created', response.get('id', 0)
         return response
Example #9
0
 def checkIfCCExists(self, sensor, debug = False):
     self._getToken(debug)
     postUrl = "{}/cc/bycustomendpoint/http".format(self.connectToURLforCC_In)
     data = {"url":'{}_for_{}'.format(sensor.getStreamId(), sensor.getDeviceId())}
     auth_header = {'Authorization':'Bearer {}\r\n'.format(self.tokenBearer), 'Accept':'application/json'}
     resp = http_client.post(postUrl, headers=auth_header,json=data, debug = debug)
     if debug: print (resp.content)
     resp.close()
     
     return resp.getStatus()[0] == 200
Example #10
0
 def create_campaign(self, title, desp=""):
     response = post(self.api_host + 'rest/campaign',
                     json={
                         'title': title,
                         'brief': desp
                     },
                     token=self.token)
     if 'id' in response:
         # print 'Campaign created id', response.get('id', 0)
         return response
Example #11
0
 def user_register(self, username, password, email):
     response = post(self.api_host + 'user/register',
                     json={
                         'username': username,
                         'password': password,
                         'email': email
                     },
                     token=self.token)
     if response:
         self.user = response
Example #12
0
 def create_selection(self, hit_id, brief):
     response = post(self.api_host + 'rest/selection',
                     json={
                         'hit_id': hit_id,
                         'brief': brief
                     },
                     token=self.token)
     if response:
         # print 'Selection created', response.get('id', 0)
         return response.get('id', 0)
Example #13
0
 def assign_user_to_campaign(self, campaign_id, role_id=2):
     response = post(self.api_host + 'rest/campaign_user',
                     json={
                         'user_id': self.user['id'],
                         'campaign_id': campaign_id,
                         'role_id': role_id
                     },
                     token=self.token)
     if 'id' in response:
         # print 'Assigned user(%d) to campaign(%d)'%(self.user['id'], campaign_id)
         return response
 def create_hit(self, type, title, description, attachment_id, campaign_id, credit, required_answer_count,
                location_id=1, min_selection_count=1, max_selection_count=1):
     response = post(self.api_host + 'rest/hit',
                     json={'type': type, 'title': title, 'description': description, 'attachment_id': attachment_id,
                           'campaign_id': campaign_id, 'credit': credit,
                           'required_answer_count': required_answer_count, 'location_id': location_id,
                           'requester_id': self.user['id'], 'min_selection_count': min_selection_count,
                           'max_selection_count': max_selection_count},
                     token=self.token)
     if response:
         print 'HIT created', response.get('id', 0)
         return response
Example #15
0
 def new_attchment_with_image(self, image_fname):
     name_from_server = post_image(self.api_host + 'image/upload',
                                   files={'file': file(image_fname, 'rb')},
                                   token=self.token)["filename"]
     resp = post(self.api_host + 'rest/attachment',
                 json={
                     'type': 'image',
                     'value': name_from_server
                 },
                 token=self.token)
     # print resp
     return resp
Example #16
0
 def user_auth(self, username, password):
     response = post(self.api_host + 'user/auth',
                     json={
                         'username': username,
                         'password': password
                     },
                     token=self.token)
     if 'token' in response:
         self.token = response['token']
         self.user = response
         # print 'User auth token', self.token
         return True
     return False
Example #17
0
def tick():
    bv = str(onboard.get_battery_voltage())
    uv = str(onboard.get_unreg_voltage())
    li = str(onboard.get_light())
    rssi = wifi.nic().get_rssi()

    aps = wifi.nic().list_aps()
    highest_rssi = -200
    nearestbssid = ""
    for a in aps:
        if (a['rssi'] > highest_rssi) and (a['rssi'] < 0):
            highest_rssi = a['rssi']
            nearestbssid = binascii.hexlify(a['bssid'])

    logfile = "log.txt"
    if not highest_rssi > -200:
        rssis = ","
        json = {"vbat": bv, "vunreg": uv, "light": li}
    else:
        rssis = str(highest_rssi) + "," + str(nearestbssid)
        r1 = stm.mem32[0x1FFF7590]
        r1 |= (stm.mem32[0x1FFF7594] << 32)
        r1 |= (stm.mem32[0x1FFF7598] << 64)
        json = {
            "vbat": bv,
            "vunreg": uv,
            "light": li,
            "rssi": str(highest_rssi),
            "bssid": str(nearestbssid),
            "uuid": "%x" % r1
        }

    if database_get("stats_upload"):
        try:
            if wifi.nic().is_connected():
                with http_client.post('http://api.badge.emfcamp.org/api/barms',
                                      json=json) as resp:
                    pass
        except OSError as e:
            print("Upload failed " + str(e))

    try:
        if not is_file(logfile):
            with open(logfile, "w") as f:
                f.write("vbat, vunreg, light, rssi, bssid \r\n")

        with open(logfile, "a") as f:
            f.write(bv + ", " + uv + ", " + li + ", " + rssis + "\r\n")
    except OSError as e:
        print("Logging failed: " + str(e))
        return "Logging failed"
Example #18
0
 def create_location(self, name, longitude, latitude, altitude=0.0):
     response = post(self.api_host + 'rest/location',
                     json={
                         'name': name,
                         'coordinate': {
                             'longitude': longitude,
                             'latitude': latitude,
                             'altitude': altitude
                         }
                     },
                     token=self.token)
     if response:
         # print 'Location created', response.get('id', 0)
         return response
Example #19
0
 def create_answer(self, hit_id, brief, attachment_id, type, location_id):
     response = post(self.api_host + 'rest/answer',
                     json={
                         'type': type,
                         'brief': brief,
                         'attachment_id': attachment_id,
                         'hit_id': hit_id,
                         'location_id': location_id,
                         'worker_id': self.user['id']
                     },
                     token=self.token)
     if response:
         # print 'Answer created', response.get('id', 0)
         return response
Example #20
0
    def pushSensorDataCloudChannels(self,
                                    enCoSensor,
                                    debug=False,
                                    forceCreateChannel=False):
        data = enCoSensor.getAsJson()
        self._getToken(debug)

        if not self.sensorHasCCDefinition(enCoSensor, debug):
            if debug: print("-- Sensor has NO CC-IN stream definition.")
            self._createCCInStreamDefinition(enCoSensor, debug)
        else:
            if forceCreateChannel:
                self._createCCInStreamDefinition(enCoSensor, debug)
                if debug:
                    print(
                        "-- Sensor HAD CC-IN stream definition! BUT RECREATED !!"
                    )
            else:
                if debug: print("-- Sensor HAS CC-IN stream definition!")

        postUrl = "{}/cc/u/{}".format(self.connectToURLforCC_In,
                                      enCoSensor.getCloudChannelCustomHTTP())

        if debug:
            print('Sending endpoint : ', postUrl)
            print('Payload : ', data)

        auth_header = {
            'Authorization': 'Bearer {}\r\n'.format(self.tokenBearer),
            'Accept': 'application/json'
        }

        #TODO : investigate why binary path causes 500 error, send as JSON seems to work ....
        resp = http_client.post(postUrl,
                                headers=auth_header,
                                json=data,
                                debug=debug)

        #        if enCoSensor.sendAsBinary() != True:
        #            resp = http_client.post(postUrl, headers=auth_header, json=data, debug = debug)
        #        else:
        #            resp = http_client.post(postUrl, headers=auth_header, binary=data, debug = debug)

        if debug: print(resp.getStatus())
        resp.raise_for_status()
        resp.close()
Example #21
0
    def _getToken(self, debug=False):
        if self.apiKey == None or self.apiSecret == None or self.userName == None:
            raise OSError('Missing authentication info!')

        if self.validUntil == None or time() >= self.validUntil:
            basic_auth = ubinascii.b2a_base64("{}:{}".format(
                self.apiKey, self.apiSecret)).decode('ascii')
            auth_header = {
                'Authorization': 'Basic {}'.format(basic_auth),
                'Accept': 'application/json'
            }

            body = 'grant_type=client_credentials&scope=openid'
            if debug: print(self.connectToURLforToken)
            resp = http_client.post(
                self.connectToURLforToken,
                headers=auth_header,
                textMsg=body,
                contentType='application/x-www-form-urlencoded',
                debug=debug)
            resp.raise_for_status()
            resp.content
            if debug:
                print('Response : ')
                print(resp.content)

            authInfo = resp.json()
            self.tokenBearer = authInfo['access_token']

            try:
                self.validUntil = time() + authInfo['expires_in']
                localtime(self.validUntil)
            except OverflowError:
                if debug:
                    print("Permanent token, setting to 1 week validity")
                self.validUntil = time() + 7 * 24 * 60 * 60

            resp.close()
            if debug:
                print("Token retrieved ! valid until {}".format(
                    localtime(self.validUntil)))
        else:
            if debug:
                print("Token still valid !  Re-using it ! {}".format(
                    self.tokenBearer))
Example #22
0
def tick():
	bv = str(onboard.get_battery_voltage())
	uv = str(onboard.get_unreg_voltage())
	li = str(onboard.get_light())
	rssi = wifi.nic().get_rssi()

	aps = wifi.nic().list_aps()
	highest_rssi = -200
	nearestbssid = ""
	for a in aps:
		if (a['rssi'] > highest_rssi) and (a['rssi'] < 0):
			highest_rssi = a['rssi']
			nearestbssid = binascii.hexlify(a['bssid'])

	logfile = "log.txt"
	if not highest_rssi > -200:
		rssis = ","
		json={"vbat" : bv, "vunreg" : uv, "light" : li}
	else:
		rssis = str(highest_rssi) + "," + str(nearestbssid)
		r1 = stm.mem32[0x1FFF7590]
		r1 |= (stm.mem32[0x1FFF7594]<<32)
		r1 |= (stm.mem32[0x1FFF7598]<<64)
		json={"vbat" : bv, "vunreg" : uv, "light" : li, "rssi" : str(highest_rssi), "bssid" : str(nearestbssid), "uuid":"%x" % r1}

	if database_get("stats_upload"):
		try:
			if wifi.nic().is_connected():
				with http_client.post('http://api.badge.emfcamp.org/api/barms', json=json) as resp:
					pass
		except OSError as e:
			print("Upload failed " + str(e))

	try:
		if not is_file(logfile):
			with open(logfile, "w") as f:
				f.write("vbat, vunreg, light, rssi, bssid \r\n")

		with open(logfile, "a") as f:
			f.write(bv + ", " + uv + ", " + li + ", " + rssis + "\r\n")
	except OSError as e:
		print("Logging failed: " + str(e))
		return "Logging failed"
Example #23
0
    def checkIfCCExists(self, sensor, debug=False):
        self._getToken(debug)
        postUrl = "{}/cc/bycustomendpoint/http".format(
            self.connectToURLforCC_In)
        data = {
            "url": '{}_for_{}'.format(sensor.getStreamId(),
                                      sensor.getDeviceId())
        }
        auth_header = {
            'Authorization': 'Bearer {}\r\n'.format(self.tokenBearer),
            'Accept': 'application/json'
        }
        resp = http_client.post(postUrl,
                                headers=auth_header,
                                json=data,
                                debug=debug)
        if debug: print(resp.content)
        resp.close()

        return resp.getStatus()[0] == 200
Example #24
0
    s = socket.socket()
    s.connect(addr)
    s.send(bytes('GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (path, host),
                 'utf8'))
    while True:
        data = s.recv(100)
        if data:
            print(str(data, 'utf8'), end='')
        else:
            break
    s.close()


connectWifi()
#do_connect()
#http_get('http://micropython.org/ks/test.html')

r = http_client.get('http://micropython.org/ks/test.html')
r.raise_for_status()
print(r.status_code)
print(r.text)  # r.content for raw bytes

r = http_client.post(
    'https://api-test.hunt-r.tech/thingworx/availability/shifts',
    json={
        "time_zone": "America/CostaRica",
        "start_date": 0,
        "end_date": 2
    })
print(r.json())
 def create_campaign(self, title, desp=""):
     response = post(self.api_host + 'rest/campaign', json={'title': title, 'brief':desp}, token=self.token)
     if 'id' in response:
         print 'Campaign created id', response.get('id', 0)
         return response
 def user_register(self, username, password, email):
     response = post(self.api_host + 'user/register',
                     json={'username': username, 'password': password, 'email': email}, token=self.token)
     if response:
         self.user = response
         print 'User created', self.user['username']
 def new_attchment_with_image(self, image_fname):
     name_from_server = post_image(self.api_host+'image/upload', files={'file':file(image_fname, 'rb')}, token=self.token)["filename"]
     resp = post(self.api_host + 'rest/attachment', json={'type': 'image', 'value':name_from_server}, token=self.token)
     print resp
     return resp
Example #28
0
print(ip)
display.puts(ip[-5:])
display.show()
utime.sleep(3)

app_id = 'YOUR_APP_ID'
api_key = 'YOUR_APP_KEY'
md5_app_id = 'xxxxxxxxxxxxxxxxxxx'	# md5(app_id)
sensors_id = [32694]
headers = {'User-Agent': app_id}
data = {'cmd': 'sensorsValues', 'uuid': md5_app_id, 'api_key': api_key, 'sensors': sensors_id}

while True:
	try:
		r = http_client.post('http://narodmon.ru/api', headers=headers, json=data)
		print(r.text)
		d = r.json()
		temp = round(d['sensors'][0]['value'])
		sign = '+' if temp >= 0 else ''

		str_display = '%s%d' % (sign, temp)
		pos = int((4*8 - len(str_display)*5) / 2)
		
		display.fill(False)
		display.puts(str_display, pos)
		display.show()
	except Exception as e:
		sys.print_exception(e)
		display.fill(False)
		display.puts('error')
Example #29
0
        if net.ssid == SSID:
            print('Network found!')
            wlan.connect(net.ssid, auth=(net.sec, PASS), timeout=5000)
            while not wlan.isconnected():
                machine.idle()  # save power while waiting
            print('WLAN connection succeeded!')
            break


#connectWifi()
do_connect()
#http_get('http://micropython.org/ks/test.html')

#r = http_client.post('https://api-test.hunt-r.tech/thingworx/availability/shifts', json={"time_zone": "America/CostaRica","start_date": 0,"end_date": 2})
#r = http_client.post('https://iot.lantern.tech/api/v1/sg1Ul5mQZxBCSndtqVuY/telemetry',json={"Device": "4D5490","Temperature": 25,"Humidity": 50})
r2 = http_client.post(
    'https://iot.lantern.tech/api/v1/sg1Ul5mQZxBCSndtqVuY/telemetry',
    json={
        "Device": "4D5490",
        "Temperature": 30,
        "Humidity": 75
    })

#print(r.json())
'''
r = http_client.get('http://micropython.org/ks/test.html')
r.raise_for_status()
print(r.status_code)
print(r.text)  # r.content for raw bytes
'''
Example #30
0
def wlanPost(URL, JSON):
    response = http_client.post(URL, json=JSON)
    print("POST response: " + str(response.status_code))
    return response
Example #31
0
client_id = '<< YOUR INFO HERE >>'
client_secret = '<< YOUR INFO HERE >>'

basic_auth = ubinascii.b2a_base64("{}:{}".format(
    client_id, client_secret)).decode('ascii')
auth_header = {
    'Authorization': 'Basic {}'.format(basic_auth),
    'Accept': 'application/json'
}
payload = 'grant_type=client_credentials&scope=openid'

print("Acquiring token")
print()
r = http_client.post("https://api.enco.io/token",
                     headers=auth_header,
                     textMsg=payload,
                     contentType='application/x-www-form-urlencoded')
print(r.text)
authInfo = r.json()
tokenBearer = authInfo['access_token']

print()
print("Using token to retrieve user information")
print()
auth_header = {
    'Authorization': 'Bearer {}\r\n'.format(tokenBearer),
    'Accept': 'application/json'
}
r = http_client.get("https://api.enco.io/userinfo?schema=openid",
                    headers=auth_header)
print(r.text)