Select Git revision
StandaloneBuildTest.cs.meta
coapclient.py 6.24 KiB
#!/usr/bin/env python
import getopt
import socket
import sys
import re, uuid
import time
import threading
import json
import bluetooth._bluetooth as bluez
import blescan
import _thread
import math
from piBeacon import BeaconEmit
from coapthon.client.helperclient import HelperClient
from coapthon.utils import parse_uri
__author__ = 'Giacomo Tanganelli'
class CoapClient():
def __init__(self): # complete
self.ip = "shmd01.iptime.org"
self.myMAC = ':'.join(re.findall('..', '%012x' % uuid.getnode()))
self.myuuid, self.operate = self.obtainMyID()
if self.operate == 1: # rpNode가 이미 한 개 이상존재하는 경우
self._beacon = BeaconEmit()
self.advertiseMe()
if self.operate != 2:
self.calculateNodePositionAtServer()
def obtainMyID(self): # complete
path = "/rpNodeInfoPath"
path = "coap://" + self.ip + path
host, port, path = parse_uri(path)
try:
tmp = socket.gethostbyname(host)
host = tmp
except socket.gaierror:
pass
client = HelperClient(server=(host, port))
try:
payload = {
'option' : 0, #obtain rpuuid from Server
'rpMAC' : self.myMAC
}
response = client.put(path, json.dumps(payload))
print((response.pretty_print()))
string = json.loads(response.payload)['rpuuid']
except KeyboardInterrupt:
print("obtainMyID Stop")
client.stop()
client.stop()
return string, json.loads(response.payload)['operate']
def advertiseMe(self): # complete
seq = self.myuuid
length = 3
string =""
for i in range(0, len(seq), 2):
string += seq[i:i+2]+" "
print(string)
print(map(''.join, zip(*[iter(seq)]*length)))
self._beacon.beacon_Start(string)
def calculateNodePositionAtServer(self): # complete
path = "/rpNodeInfoPath"
path = "coap://" + self.ip + path
host, port, path = parse_uri(path)
try:
tmp = socket.gethostbyname(host)
host = tmp
except socket.gaierror:
pass
client = HelperClient(server=(host, port))
try:
payload = {
'option' : 1, # obtain my position from Server.
'rpuuid' : self.myuuid
}
response = client.put(path, json.dumps(payload))
print((response.pretty_print()))
if json.loads(response.payload)['operate'] == 0: # Postion 계산이 불가능한 경우
print("impossble position calculation")
except KeyboardInterrupt:
print("obtainMyID Stop")
client.stop()
client.stop()
def putBLEInfo(self): # complete
dev_id = 0
try:
self.sock = bluez.hci_open_dev(dev_id)
print("ble thread started")
except:
print("error accessing bluetooth device...")
sys.exit(1)
blescan.hci_le_set_scan_parameters(self.sock)
blescan.hci_enable_le_scan(self.sock)
path = "/bleInfoPath"
payload = []
path = "coap://" + self.ip + path
host, port, path = parse_uri(path)
try:
tmp = socket.gethostbyname(host)
host = tmp
except socket.gaierror:
pass
client = HelperClient(server=(host, port))
try:
while True :
payload = []
returnedList = blescan.parse_events(self.sock, 50)
for beacon in returnedList:
beaconInfo = [str(x) for x in beacon.split(',') if x.strip()]
if beaconInfo[1][:8] == "52528282":
print("scanned : "+ str(beaconInfo))
regiRelThread = threading.Thread(target = self.regiRelWithNewPi, args=([beaconInfo]))
regiRelThread.start()
continue
jsonpayload = self.mkJsonbeaconInfo(beaconInfo)
if jsonpayload['distance'] < 40:
payload.append(jsonpayload)
response = client.put(path, json.dumps(payload))
print((response.pretty_print()))
except KeyboardInterrupt:
print("PutBLEInfo Stop")
client.stop()
client.stop()
def mkJsonbeaconInfo(self, info): # complete
n = 2.05
h = 0
ad = 0
distance = math.pow(10, (float(info[4]) - float(info[5])) / (10 * n))
if distance < h:
ad = 0
else:
ad = math.sqrt(distance * distance - h * h)
payload = {
'rpuuid' : self.myuuid,
'userMAC' : info[0],
'useruuid' : info[1],
'distance' : ad,
'updateTime' : time.time()
}
return payload
def regiRelWithNewPi(self, info): # complete
#새로운 rasbPi를 찾은 경우 새로운 rasbPi를 위치측정기로 사용하기 위해서 server에 관련 정보를 저장하는 method
path = "/rpGraphInfoPath"
path = "coap://" + self.ip + path
host, port, path = parse_uri(path)
try:
tmp = socket.gethostbyname(host)
host = tmp
except socket.gaierror:
pass
client = HelperClient(server=(host, port))
try:
response = client.put(path, json.dumps(self.mkJsonRpgraphInfo(info)))
print((response.pretty_print()))
except KeyboardInterrupt:
print("obtainMyID Stop")
client.stop()
client.stop()
def mkJsonRpgraphInfo(self, info): # complete
n = 2.05
distance = math.pow(10, ((float(info[4]) - float(info[5])) / (10 * n)))
payload = {
'v1' : self.myuuid,
'v2' : info[1],
'distance' : distance
}
return payload
def main():
measuringDevice = CoapClient()
putBLEInfoThread = threading.Thread(target = measuringDevice.putBLEInfo)
putBLEInfoThread.start()
putBLEInfoThread.join()
if __name__ == "__main__":
main()