Pubblicazione delle misurazioni del contatore Geiger su Adafruit IO (MQTT)

Dopo aver messo online il GMC-320 con il Raspberry ho pensato di inviare i dati anche alla dashboard di Adafruit IO che permette di visualizzarli come grafici e farne delle analisi basilari, con uno script in Python ho quindi risolto il problema:

#!/usr/bin/python
# -*- coding: utf-8 -*-s
import os # directory methods
import struct
import datetime
import time
import serial
import sys
import ftplib

from subprocess import check_output
from re import findall
import psutil
import sys
import time

from Adafruit_IO import MQTTClient
ADAFRUIT_IO_KEY = 'key-adafruit-io'
ADAFRUIT_IO_USERNAME = 'your-username'
feed_cpm = 'your.feed'

gmc = serial.Serial('/dev/ttyUSB0', 115200, timeout= 3) #device

def disconnected(client):
# Disconnected function will be called when the client disconnects.
print('Disconnected from Adafruit IO!')
sys.exit(1)

def connected(client):
# Connected function will be called when the client is connected to Adafruit IO.
# This is a good place to subscribe to topic changes. The client parameter
# passed to this function is the Adafruit IO MQTT client so you can make
# calls against it easily.
print('Listening for changes on ', group_name)
# Subscribe to changes on a group, `group_name`
#client.subscribe_group(group_name)

def message(client, topic_id, payload):
# Message function will be called when a subscribed topic has a new value.
# The topic_id parameter identifies the topic, and the payload parameter has
# the new value.
print('Topic {0} received new value: {1}'.format(topic_id, payload))

def getCPM(gmc): 
gmc.write(b'<GETCPM>>')
dat = gmc.read(2)
try:
#gv = ord(dat[0]) << 8 | ord(dat[1])
gv = dat[0] << 8 | dat[1]
except IndexError:
gv = ord("\x00")
return gv

def gmcCommand(gmc, cmd, returnlength, byteformat = True):
try: #send command
gmc.write(cmd)
except: 
print ("\nSend Error")#, sys.exc_info()
gmc.close()
sys.exit(1)
try: #read data
rtn = gmc.read(returnlength)
except:
print ("\nReceive ERROR")#, sys.exc_info()
gmc.close()
sys.exit(1)
if byteformat: rtn = map(ord,rtn) # convert string to list of int
return rtn

# Create an MQTT client instance.
client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

# Setup the callback functions defined above.
client.on_connect = connected
client.on_disconnect = disconnected
client.on_message = message

# Connect to the Adafruit IO server.
client.connect()

client.loop_background()
# Now send new values every 5 seconds.
#print('Publishing a new message every 5 seconds (press Ctrl-C to quit)...')
value = getCPM(gmc)
print('Publishing {0} to {1}.'.format(value, feed_cpm))
client.publish(feed_cpm, value)

def getClock():
clockval="<SETDATETIME[YYMMDDHHMMSS]>>"#set gmc clock cmd
datenow = "{:%m/%d/%Y %H:%M:%S}".format(datetime.datetime.now())
return datenow

def getTEMP(gmc): 
gmc.write(b'<GETTEMP>>')
dat = gmc.read(4)
try:
#i = ord(dat[0]) #ord(dat[0])<< 8 | ord(dat[1])
i = dat[0]
#d = ord(dat[1])
d = dat[1]
tCelcius = "{0}.{1}".format(i,d)
tFarenheit=float(tCelcius)*1.4+32
gv="{0},{1}".format(tCelcius,tFarenheit)
except IndexError:
gv =ord("0")
return gv

cl = getClock()

try:
cl = getClock()
currentCPM=value
cpm = "{0},{1}\n".format(cl,currentCPM)
print ("{0} {1}".format(cl,currentCPM))
tmp = "{0}".format(getTEMP(gmc))
tCel =tmp.split(',')[0]
tF = tmp.split(',')[1]
except KeyboardInterrupt:
pass

il risultato si può vedere a questo link

Link al contatore Geiger: AMAZON

Post Disclaimer

Creative common license BY-NC_SA

Informazioni Importanti

Note generali: Le informazioni contenute in questo articolo sono di carattere informativo e rispecchiano le opinioni personali del autore. Tutte le guide nel sito vengono proposte "as it is" puramente a scopo didattico. L'utente che accetta di seguirne i passaggi si assume ogni responsabilità in caso di guasto/malfunzionamento o altro problema come conseguenza della modifica.

Link di affiliazione e contenuti promozionali: Nei post di iu2frl.it posso includere collegamenti a rivenditori. Posso ricevere una piccola commissione dal rivenditore se effettui un acquisto dopo aver fatto clic su uno di questi link. I post non sono espressamente sponsorizzati da rivenditori, editori, promotori o produttori, se non diversamente specificato chiaramente e tutte le decisioni editoriali sono prese esclusivamente dagli autori dei singoli articoli.

Contenuti riguardanti regolamenti e/o normative: Eventuali riferimenti a normative non costituiscono valore legale, si tratta di libere interpretazioni ed estratti di circolari corredate da eventuali commenti, si invitano tutti gli utenti a verificare la veridicità di tali informazioni sugli organi ufficiali di riferimento, nessuna colpa o responsabilità può essere data agli autori degli articoli.

Licenza di utilizzo: Tutti i contenuti vengono condivisi con licenza CC BY-NC-SA 4.0: Questa licenza consente ad altri di remixare, adattare e sviluppare i contenuti in modo non commerciale, purché accreditino l'autore originale e concedano in licenza le loro nuove creazioni con gli stessi termini. Per maggiori informazioni visitare il sito Creative Commons.

Important Informations

General notes: The information contained in this article is of an informative nature and reflects the personal opinions of the author. All the guides/tutorial on the website are offered "as it is" for educational purposes only. The user who agrees to follow the steps assumes all responsibility in case of failure/malfunctioning or other problem as a result of the modification.

Affiliate links and promotional products: In some posts of iu2frl.it I can include links to resellers. I can get a small commission from the reseller if you make a purchase after clicking on one of these links. The posts are not expressly sponsored by resellers, publishers, promoters or producers, unless otherwise clearly specified and all editorial decisions are made solely by the authors of the individual articles.

Contents about rules and laws: Some articles may contain portions or whole laws or rules regarding specific areas, these kind of content are meant to be indicative only, no responsability can be given to the authors. Always refer to official sources when looking for rules or laws.

Contents licenses: All the contents are published as CC BY-NC-SA 4.0: This license lets others remix, adapt, and build upon your work non-commercially, as long as they credit you and license their new creations under the identical terms.. For more informations please visit Creative Commons website.

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *