class HologramSender: def __init__(self): self.hologram = HologramCloud(dict(), network='cellular') self.connected = self.hologram.network.connect() if self.connected == False: print(' Failed to connect to cell network') def __del__(self): self.hologram.network.disconnect() def foundPerson(self, name, ID, location, phone): payload = self.formatPayload(name, ID, location, phone) return self.sendAlert() def formatPayload(self, name, ID, location, phone): payloadDict = {} payloadDict['name'] = name payloadDict['ID'] = ID payloadDict['phoneNumber'] = phone payloadDict['location'] = location payloadDict['datetime'] = datetime.datetime.now().strftime( "%Y-%m-%d %H:%M:%S") jsonPayload = json.dumps(payloadDict) self.payload = jsonPayload def sendAlert(self): self.responseCode = self.hologram.sendMessage(self.payload, topics=["waldo-edge"]) return self.hologram.getResultString(self.responseCode)
# respond with the cellular position if RESPOND_WITH[1] == 'g' and gpsLatitude != 0.0: latitude, longitude = gpsLatitude, gpsLongitude origin = 'GPS' # Otherwise the requested data is the cellular position. # In the future the default behavior might change so # let's stick with 'c' means cellular position here and # the default is the same else: latitude, longitude = getCoordinates() origin = 'Cellular' # 's' is indicating that the response needs to be an SMS if RESPOND_WITH[0] == 's': response = origin + ' coordinates of your bike: https://maps.google.com/maps?q=' + str(latitude) + ',' + str(longitude) topic = 'sms' # Otherwise the response needs to be an SMS. # In the future the default behavior might change so # let's stick with 'e' means reponse needs to be and e-mail # and the default behavior is the same else: response = '{"latitude":"' + str(latitude) + '","longitude":"' + str(longitude) + '","origin":"'+ origin +'"}' topic = 'email' print 'Response: ' + response # Sending the data to the Hologram Cloud. It will do the # necessary routing, data handling response_code = hologram.sendMessage(response, topic) if 'Message sent successfully' == hologram.getResultString(response_code): print 'Message sent successfully' else: print 'Failed to send message'
print "* Note: You can obtain device keys from the Devices page" print "* at https://dashboard.hologram.io" print "" device_id = raw_input("What is your device id? ") private_key = raw_input("What is your private key? ") credentials = {'device_id': device_id, 'private_key': private_key} hologram = HologramCloud(credentials, enable_inbound=False, authentication_type='totp') print 'Hologram SDK version:' print hologram.version print '' print 'Cloud type: ' + str(hologram) print '' print 'Network type: ' + hologram.network_type print '' recv = hologram.sendMessage("YESYESYES!", topics=["YES"], timeout=6) print 'RESPONSE CODE RECEIVED: ' + str(recv) print 'RESPONSE MESSAGE: ' + hologram.getResultString(recv) print '' print 'Testing complete.' print ''
sys.path.append("..") sys.path.append("../..") from Hologram.HologramCloud import HologramCloud if __name__ == "__main__": print "" print "" print "Testing Hologram Cloud class..." print "" print "* Note: You can obtain device keys from the Devices page" print "* at https://dashboard.hologram.io" print "" logging.basicConfig(level=logging.DEBUG, format="%(levelname)s: %(message)s") hologram = HologramCloud(dict(), authentication_type='sim-otp', network='cellular') result = hologram.network.connect() if result == False: print 'Failed to connect to cell network' recv = hologram.sendMessage("one two three!", topics = ["TOPIC1","TOPIC2"], timeout = 3) print 'RESPONSE MESSAGE: ' + hologram.getResultString(recv) hologram.network.disconnect()
from Hologram.HologramCloud import HologramCloud import Adafruit_DHT credentials = {'devicekey': 'top_secret'} hologram = HologramCloud(credentials, network='cellular') result = hologram.network.connect() if result == False: print ' Failed to connect to cell network' sensor = Adafruit_DHT.DHT11 pin = 4 humidity, temperature = Adafruit_DHT.read_retry(sensor, pin) humidity, temperature = Adafruit_DHT.read_retry(sensor, pin) response_code = hologram.sendMessage("h:" + str(humidity) + "t:" + str(temperature)) print hologram.getResultString( response_code) # Prints 'Message sent successfully'. hologram.network.disconnect()
interpreter.set_tensor(input_details[0]['index'], input_data) print("invoke interpreter") interpreter.invoke() # The function `get_tensor()` returns a copy of the tensor data. # Use `tensor()` in order to get a pointer to the tensor. output_data = interpreter.get_tensor(output_details[0]['index']) results = np.squeeze(output_data) print(results) waterStressLevel = int(np.argmax(results)) percentConfident = results[waterStressLevel] * 100 print("Time:", curr.strftime("%d_%m_%Y_%H_%M_%S")) print("CPUTemp", cpu_temp) print("Saving image...") data = { "DEVICE_ID": 1, "DEVICE_STATUS": "On", "WATER_STRESS_LEVEL": waterStressLevel, "CPU_TEMPERATURE": cpu_temp, "DATE_1": currDate, "TIME_1": currTime, "SD": disk_percent_used, "SD_free": disk_free } formatted_data = json.dumps(data, separators=(" ", ":")) recv = hologram.sendMessage(formatted_data) # Send message to hologram cloud print("Recieved Code:", recv) print("0 Means Succesful Transmission") subprocess.run("sudo hologram network disconnect", shell=True) sleep(20)
print '' print "Testing Hologram Cloud class..." print '' print "* Note: You can obtain device keys from the Devices page" print "* at https://dashboard.hologram.io" print '' device_key = raw_input('What is your device key? ') credentials = {'devicekey': device_key} hologram = HologramCloud(credentials, enable_inbound = False) print '' hologram.event.broadcast('network.disconnected') recv = hologram.sendMessage("one!", topics = ["TWO MORE TIMES","TOPIC TOPIC"]) # Send advanced message print "RESPONSE CODE RECEIVED: " + str(recv) recv = hologram.sendMessage("two!", topics = ["TWO MORE TIMES","TOPIC TOPIC"]) # Send advanced message print "RESPONSE CODE RECEIVED: " + str(recv) recv = hologram.sendMessage("three!", topics = ["TWO MORE TIMES","TOPIC TOPIC"]) # Send advanced message print "RESPONSE CODE RECEIVED: " + str(recv) hologram.event.broadcast('network.connected') print '' print 'Testing complete.' print ''
class GPSD(Daemon): """ This is the main communications controller this collects GPS data and if we have moved more than 0.75 miles from the last GPS location it gets sent to the back-end API. """ def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'): Daemon.__init__(self, pidfile, stdin, stdout, stderr) self.location = (0, 0) truckFile = open("/etc/cl-lcr-truck", "r") uuidFile = open("/etc/cl-lcr-uuid", "r") self.truck = truckFile.readline().rstrip() self.uuid = uuidFile.readline().rstrip() uuidFile.close() self.lastMsg = "" truckFile.close() self.multiplier = 1 currentDT = datetime.datetime.now() if currentDT.hour > 18 or currentDT.hour < 8: self.multiplier = 20 else: self.multiplier = 2 def addLocation(self, lat, lon): try: elapsed_time = time.time() - self.start_time if lat is None or lon is None: if elapsed_time > (230 * self.multiplier): self.start_time = time.time() self.callGps(True) return False moved = distance.distance(self.location, (lat, lon)).miles if elapsed_time > (120 * self.multiplier): if moved > 0.9: self.compressGps(lat, lon) elif elapsed_time > (880 * self.multiplier): self.compressGps(lat, lon) except: print "Add Location Error" pass def compressGps(self, lat=None, lon=None): try: currentDT = datetime.datetime.now() if currentDT.hour > 18 or currentDT.hour < 8: self.multiplier = 20 else: self.multiplier = 2 self.start_time = time.time() call("/usr/local/bin/node /root/cl-lcr-daemon/gpsd/convert.js", shell=True) time.sleep(1) gpsFile2 = open("/root/gps.out", "r") message = gpsFile2.readline().rstrip() gpsFile2.close() if message != self.lastMsg: self.hologram.sendMessage(message, topics=["gps"], timeout=20) self.lastMsg = message except: print "Compress GPS Error" pass def callGps(self, forceHologram=None): try: if self.location is None or self.location[ 0] is None or self.location[ 1] is None or forceHologram is not None: location = self.hologram.network.location i = 0 while location is None and i < 5: time.sleep(1) location = self.hologram.network.location if location is None: i += 1 else: i = 10 if location is not None: self.compressGps(location.latitude, location.longitude) else: self.compressGps(self.location[0], self.location[1]) except: pass def run(self): self.start_time = time.time() - 200 self.hologram = HologramCloud({'devicekey': 'ujk{]5pX'}, network='cellular') if self.hologram.network.getConnectionStatus() != 1: self.hologram.network.disconnect() time.sleep(1) try: result = self.hologram.network.connect() if result == False: sys.stderr.write("Failed to connect to cell network\n") else: self.hologram.openReceiveSocket() self.hologram.event.subscribe('message.received', self.receivedMessage) except: sys.stderr.write("connection error\n") pass while True: time.sleep(220 * self.multiplier) self.compressGps() def tail(self, f, n, offset=0): data = "" try: with open(f, 'r') as myfile: data = myfile.read() myfile.close() if data != "": n = int(n) * -1 data = data[n:] except: data = "error" pass return data def receivedMessage(self): try: message = self.hologram.popReceivedMessage() except: message = hologram.popReceivedMessage() if ":" in message: parts = message.split(':') else: message = zlib.decompress(message) if ":" in message: parts = message.split(':') else: sys.stderr.write("Invalid message\n") return False if parts[0] == "gps": self.start_time = time.time() - 1000 self.callGps() elif parts[0] == "gpsd": self.start_time = time.time() - 1000 self.callGps(True) elif parts[0] == "cmd": try: sys.stderr.write("Running CMD: " + str(parts[1]) + "\n") call(parts[1], shell=True) except: sys.stderr.write("Failed CMD" + str(parts[1]) + "\n") elif parts[0] == "tail": message = self.tail(parts[2], parts[1]) message = base64.b64encode( zlib.compress( ("tail:" + parts[2] + ":" + str(message)).encode('utf8'), 9)) self.hologram.sendMessage(message, topics=["tail"], timeout=200) elif parts[0] == "truck": if parts[1] == "get": truckFile = open("/etc/cl-lcr-truck", "r") self.truck = truckFile.readline().rstrip() truckFile.close() elif parts[1] == "set": truckFile = open("/etc/cl-lcr-truck", "w") truckFile.truncate() truckFile.write(parts[2]) truckFile.close() self.truck = parts[2] self.hologram.sendMessage(base64.b64encode( zlib.compress(("truck:" + self.truck).encode('utf8'), 9)), topics=["tail"])
print(i) # co2 sensor control ser.flushInput() time.sleep(.5) ser.write("\xFE\x44\x00\x08\x02\x9F\x25") time.sleep(.5) resp = ser.read(7) high = ord(resp[3]) low = ord(resp[4]) co2 = (high * 256) + low cReadings.append(co2) #print "closed lid CO2 = " +str(co2) print(cReadings) #send to hologram cloud responce_code = hologram.sendMessage("closed lid: " + str(cReadings)) #responce_code = hologram.sendMessage("closed lid: "+ str(co2)) time.sleep(.1) # Servo Open servo.min() print "...opening chamber..." time.sleep(20) servo.detach() #time.sleep(60) time.sleep(3540) oReadings = [] for i in range(60): print(i) # co2 read closed
# Copyright 2016 - Hologram (Konekt, Inc.) # # LICENSE: Distributed under the terms of the MIT License # import sys sys.path.append(".") sys.path.append("..") sys.path.append("../..") from Hologram.HologramCloud import HologramCloud if __name__ == "__main__": print "" print "" print "Testing Hologram Cloud class..." print "" print "* Note: You can obtain device keys from the Devices page" print "* at https://dashboard.hologram.io" print "" hologram = HologramCloud(dict(), network='cellular') print 'Cloud type: ' + str(hologram) recv = hologram.sendMessage('one two three!', topics=['TOPIC1', 'TOPIC2'], timeout=3) print 'RESPONSE MESSAGE: ' + hologram.getResultString(recv)
start_char = ((n - 1) * 5000) end_char = (n * 5000) section_of_image = encoded_string[start_char:end_char] message = "".join([ "stamp", divider, str(timestamp), divider, "cluster_order", divider, str(n), divider, "number_of_fragments", divider, str(num_of_messages), divider, "total_character_count", divider, str(character_count), divider, "content", divider, section_of_image ]) sending_msg_string = "Sending message %d" % (n) logger.debug(sending_msg_string) response_code = hologram.sendMessage(message, topics=["pi-one"]) hologram_result_string = hologram.getResultString(response_code) logger.debug(hologram_result_string) sleep(2) final_modem_disconnect = hologram.network.modem.disconnect() final_network_disconnect = hologram.network.disconnect() final_disconnections_string = "FINAL DISCONNECTIONS => Network: " + str( final_network_disconnect) + " Modem: " + str( final_modem_disconnect) logger.debug(final_disconnections_string) if os.path.exists(image_path): os.remove(image_path) file_removed_string = image_title + " removed."
GPIO.setmode(GPIO.BCM) #Configuramos los pines GPIO como BCM PIR_PIN = 17 GPIO.setup(PIR_PIN, GPIO.IN) #Lo configuramos como entrada #GPIO.setup(17, GPIO.OUT) #Configuramos el pin 17 como salida (para un led) hologram = HologramCloud(dict(), network='cellular') print 'Cloud type: ' + str(hologram) try: while True: #Iniciamos un bucle infinito if GPIO.input(PIR_PIN): # GPIO.output(17,True) #Encendemos el led time.sleep(0.5) #Pausa de 1 segundo timex = strftime("%d-%m-%Y %H:%M:%S", gmtime()) #Creamos una cadena de texto con la hora timex = timex + " MOVIMIENTO DETECTADO" #La sacamos por pantalla print timex time.sleep(1) #Pausa de 1 segundo recv = hologram.sendMessage(timex, topics = ['PIR_SENSOR'], timeout = 3) print 'RESPONSE MESSAGE: ' + hologram.getResultString(recv) # GPIO.output(17,False) #Apagamos el led time.sleep(1) #Pausa de 1 segundo y vuelta a empezar except KeyboardInterrupt: #Si el usuario pulsa CONTROL + C... print "quit" #Anunciamos que finalizamos el script GPIO.cleanup() #Limpiamos los pines GPIO y salimos
lightOn(PIN) LED_STATE = True return True try: while True: ## Button pressed if GPIO.input(BTN_PIN) == False: ## toggle LED result = toggleLed(LED_PIN) ## send event message to the cloud hologram.sendMessage("light turned " + result, [TOPIC]) ## Check inbound SMS messages recv = hologram.popReceivedSMS() if recv is True: if recv == 'on': ledOn(LED_PIN) elif recv == 'off': ledOff(LED_PIN) elif recv == 'blink': blink(LED_PIN) finally: hologram.disableSMS() GPIO.output(LED_PIN,False) ## Switch off LED
from Hologram.HologramCloud import HologramCloud credentials = {'devicekey': '12345a7b'} if __name__ == '__main__': cloud = HologramCloud(dict(), network='cellular') print('HOLOGRAM') print cloud.version # Prints 0.7.0 print cloud.network_type # Prints either 'Network Agnostic Mode' or 'Cellular' hologram = HologramCloud(credentials, network='cellular') print('sending message...') recv = cloud.sendMessage("hi there!", topics=["TOPIC1", "TOPIC2"])
sleep(hold) ## Function to toggle LED def toggleLed(PIN): global LED_STATE if LED_STATE is True: lightOff(PIN) LED_STATE = False return False else: lightOn(PIN) LED_STATE = True return True try: while True: ## Button pressed if GPIO.input(BTN_PIN) == False: ## toggle LED result = toggleLed(LED_PIN) ## send event message to the cloud hologram.sendMessage("light turned " + str(result), [TOPIC]) finally: GPIO.output(LED_PIN,False) ## Switch off LED GPIO.cleanup() ## reset all pins
print "" print "* Note: You can obtain device keys from the Devices page" print "* at https://dashboard.hologram.io" print "" device_key = raw_input("What is your device key? ") credentials = {'devicekey': device_key} hologram = HologramCloud(credentials, enable_inbound=False) print 'Hologram SDK version:' print hologram.version print '' print 'Cloud type: ' + str(hologram) print '' print 'Network type: ' + hologram.network_type print '' recv = hologram.sendMessage("one two three!", topics=["TWO MORE TIMES", "TOPIC TOPIC"], timeout=6) print 'RESPONSE CODE RECEIVED: ' + str(recv) print 'RESPONSE MESSAGE: ' + hologram.getResultString(recv) print '' print 'Testing complete.' print ''
hologram = HologramCloud(devicekey, network='cellular', enable_inbound=False) hologram.network.connect() ## connect from the cellular netowork try: while True: if GPIO.input(BTN_PIN) == False: ## Exercise 05 - send data to Hologram's cloud through WiFi lightOn(LED_PIN) message = json.dumps({ 'h': getHum(DHT_PIN), 't': getTemp(DHT_PIN), 'l': getLux(LUX_MCP) }) sent = hologram.sendMessage(message) lightOff(LED_PIN) if sent == 0: print 'Success! Message sent to the cloud.' print message else: print 'Error type [' + sent + ']' print 'Error descriptions: https://hologram.io/docs/reference/cloud/python-sdk/#-sendmessage-message-topics-none-timeout-5-' finally: GPIO.output(LED_PIN, False) ## Switch off LED GPIO.cleanup() ## reset all pins hologram.network.disconnect( ) ## Exercise 06 - disconnect from the cellular network
print mensaje_instruccion recv = cloud.sendSMS("+14439044822", mensaje_instruccion) dueno.activar_sistema(cloud) while True: sms = dueno.a_d_sms(cloud) #print sms if sms == 'D': activo = 'D' alerta = False ciclo = 2 gpio.output(13, False) response = 'Sistema de seguridad desactivado' recv = cloud.sendMessage(response, topics=['TRIGGER_DESACTIVAR'], timeout=3) print cloud.getResultString(recv) elif sms == 'A': activo = 'A' response = 'Sistema de seguridad activado' recv = cloud.sendMessage(response, topics=['TRIGGER_ACTIVAR'], timeout=3) print cloud.getResultString(recv) #Si es 'U' se mantiene el valor de activo if alerta == True: ciclo = 10 #print "Modo Alerta" gsmlatitude, gsmlongitude = getCoordinates() response = 'Coordenadas de la maquina: https://maps.google.com/maps?q=' + str(
#!/usr/bin/python # -*- coding: utf-8 -*- import sys, os os.system("sh /home/pi/rpifiles/vedirect/updatevars.sh") sys.path.insert(0, '/home/pi/rpifiles/RPI_SSD1306/') import sigpower from Hologram.HologramCloud import HologramCloud hologram = HologramCloud(dict(), network='cellular') var_vpv = sigpower.var_vpv var_batt = sigpower.var_batt var_bars = sigpower.var_bars var_op = sigpower.var_op result = hologram.network.connect() if result == False: print ' Failed to connect to cell network' response_code = hologram.sendMessage("Panel is " + str(var_vpv) + " - Batt is " + str(var_batt) + " - Network is " + str(var_op) + " with " + str(var_bars) + " bars of signal", topics=["Gulch"], timeout=10) print hologram.getResultString(response_code) hologram.network.disconnect()
from Hologram.HologramCloud import HologramCloud import os credentials = {'devicekey': '8K0Dyq*7'} hologram = HologramCloud(credentials, network='cellular') connected = 0 while not (connected == 1): os.system("sudo hologram network disconnect") if connected == 0: print "Not Connected (%d)\n -> Connecting" % (connected) hologram.network.connect(timeout=10) else: print "Trying to Reconnect (%d)" % (connected) hologram.network.disconnect() hologram.network.connect(timeout=10) connected = hologram.network.getConnectionStatus() print "Connected!" msg_err = hologram.sendMessage("I'm alive", timeout=7) if msg_err == 0: print "WE OUT HERE!!!!" else: print hologram.getResultString(msg_err)
from Hologram.HologramCloud import HologramCloud hologram = HologramCloud(dict(), network='cellular') result = hologram.network.connect() if result == False: print ' Failed to connect to cell network' response_code = hologram.sendMessage("hello, world 1!") print hologram.getResultString( response_code) # Prints 'Message sent successfully'. response_code = hologram.sendMessage("hello, world 2!", topics=["example-topic"]) hologram.network.disconnect()
print("Particles > 5.0um / 0.1L air:", particles_50um) print("Particles > 10 um / 0.1L air:", particles_100um) print("---------------------------------------") # Send data to Hologram #....Open connection to Hologram result = hologram.network.connect() if result == False: print ' Failed to connect to cell network' #....Send json string to Hologram # dataString = "hello, world!" # For testing dataString = json.dumps({ "time": Time, "temperature": str(bme280.temperature), "relativeHumidity": str(bme280.humidity), "pressure": str(bme280.pressure), "PM2.5": str(pm25_env) }) response_code = hologram.sendMessage(dataString) print hologram.getResultString( response_code) # Prints 'Message sent successfully'. #....Close connection to hologram.network.disconnect() # Wait for 10 seconds time.sleep(10) # delay ten seconds # Reset PM sensor buffer buffer = buffer[32:] f = open(fn, 'a')
def waterlevel(data): if data.startswith('<info> app: WL data:'): waterout = int(data[20:]) percentfull = ((waterout) / 177) gallons = (5.5 * percentfull) return gallons while (1): # Wait until there is data waiting in the serial buffer if (serialPort.in_waiting > 0): # Read data out of the buffer until a carraige return / new line is found serialString = serialPort.readline() message = (serialString.decode('Ascii')) # Print the contents of the serial data print(message) #Water logic if connected gallons = waterlevel(message) print('Gallons in Bucket:' + str(gallons)) #Send information to the cloud hologram = HologramCloud(dict(), network='cellular') print('Cloud type: ' + str(hologram)) payload = {"WaterLevel": gallons} recv = hologram.sendMessage(json.dumps(payload)) time.sleep(30)
class HologramDemo(object): def __init__(self): credsfile = os.path.dirname(os.path.realpath(__file__)) +\ '/credentials.json' #credfile = '/home/pi/demo-touchscreen/credentials.json' with open(credsfile, 'r') as f: self.credentials = json.load(f) self.init_hologram() def init_hologram(self): self.hologram = HologramCloud(self.credentials, network='cellular', authentication_type='csrpsk') self.hologram.enableSMS() # FUNCTIONS def convert_location_into_json(location_obj): location_list = [ 'date', 'time', 'latitude', 'longitude', 'altitude', 'uncertainty' ] response_list = [ location_obj.date, location_obj.time, location_obj.latitude, location_obj.longitude, location_obj.altitude, location_obj.uncertainty ] location_data = dict(zip(location_list, response_list)) return json.dumps(location_data) def run_modem_location(self): location_obj = hologram.network.location if location_obj is None: return 'NA' else: return convert_location_into_json(location_obj) def checkForSMS(self): sms_obj = self.hologram.popReceivedSMS() if sms_obj is not None: print u"Got SMS: ", sms_obj.message def start(self): print 'PYTHON STARTED' def sendData(self): print('Sending data to cloud') self.hologram.network.connect() self.hologram.sendMessage('Hello Nova') self.hologram.network.disconnect() print('Done') def sendSMS(self, destination_number): print('Sending SMS to %s' % destination_number) self.hologram.network.connect() self.hologram.sendSMS(destination_number, "Hello Nova") self.hologram.network.disconnect() print('Done') def sendSensor(self): print 'PYTHON SENSOR' ##hologram.disableSMS() exit() def demoLoop(self): print("Starting Demo") try: while True: rd, wr, er = select.select([sys.stdin], [], [], 5) if rd: line = sys.stdin.readline() if line == "sendData\n": self.sendData() elif line == "sendSMS\n": secondLine = sys.stdin.readline() print secondLine self.sendSMS(secondLine.rstrip()) elif line == "sendSensor\n": self.sendSensor() else: print 'dunno' self.checkForSMS() except Exception: print(traceback.format_exc()) self.hologram.network.disconnect()