Fikret
Published

Telegram Supported Current Probe

This is an isolated current probe to measure AC or DC current of load. It has two seperated channel for high and low voltage measurement.

IntermediateWork in progress10 hours169
Telegram Supported Current Probe

Things used in this project

Hardware components

PCBWay Custom PCB
PCBWay Custom PCB
×1
Altınkaya Electronic Enclosure
×1

Software apps and online services

Telegram

Story

Read more

Code

Current Probe

Python
this file is main.py
#Bismillahirrahmanirrahim

# coding=<utf-8>
from periphery import SPI
from datetime import datetime
from time import sleep
from periphery import GPIO
import serial
import os
from sabit import sabit
import telepot
from telepot.loop import MessageLoop
from matplotlib import pyplot as plt
# numpy as np
#import pandas as pd

def readLan():
    wlan0Mac=""
    wlan0Ip=""
 
    ipAddr=""
    mac=""
    
    data = os.popen("ifconfig wlan0").read()
    #print(data)
    dataP = data.split("\r")
    for i in dataP:
      #print("Data: {}".format(i))
      if "wlan0" in i:
          #print("wlan0")
          lines=i.split("\n")
          for text in lines:
            if "ether" in text:
              mac=text.lstrip().split(" ")[1]
          #print("mac: {}".format(mac))
          wlan0Mac=mac
          wlan0Ip=""
          for text in lines:
            if "inet " in text:
              ipAddr=text.lstrip().split(" ")[1]
          #print("ipAddr: {}".format(ipAddr))
          if ipAddr!="":
            wlan0Ip=ipAddr
    return([wlan0Mac, wlan0Ip])

def readTxt(file):
    deger = []
    with open(file,"r+") as dosya:
        content = dosya.read()
        #print(len(content))
        #print(type(content))
        
        data = content.split("\n")
        print(len(data))
        for i in range(7):
            data.pop(0)
        data.pop(-1)
        for i in data:
            deger.append(i.split("\t\t"))
        #print(len(deger))
        #print(len(deger[0]))
        
        return deger
            
    #return data
def makeSummary(chatId, begin=0, end=0 ):
    data = readTxt(sabitler.file)

    value = []
    zaman = []
    zcd = []
    if begin > 0 and end > 0:
        data = data[begin:end]
    elif begin > 0:
        data = data[begin:]
    elif end > 0:
        data = data[:end]
        
    for i in data:
        x, y, z = i
        value.append(float(x))
        zaman.append(y)
        zcd.append(1 * int(z))
    
    fig, ax = plt.subplots( )
    ax.plot(value)
    ax.plot(zcd)
    #fig.show()
    fig.savefig(sabitler.telepotImg)
    plt.close(fig)
    #bbox_inches='tight')
    
    
    bot.sendPhoto(messageId, photo = open(sabitler.telepotImg, "rb"),caption="Telegram id:{} Current Probe Summary".format(messageId))
    #plt.show()

# telegram Bot
def handle(msg):
    chatId = msg['chat']['id']
    command = msg['text']
    
    global messageId
    global sendSummary
    global begin
    global end
    global readCh
    global readEn
    global compute
    global telegramData
    global telegramMessage
    
    
    
    messageId = chatId
    print ("Got command: {} from {}".format( command, chatId))


    if command.startswith("/hi"):
        #bot.sendDocument(chat_id, document=open("xls/query.xlsx", "rb"), caption="query.xlsx")
        #bot.sendPhoto(chat_id,photo=open(photoName, "rb"),caption="Telegram id:{} Query".format(chat_id))
        bot.sendMessage(chatId, "Merhaba")
        
    elif command.startswith("/summary"):
        sendSummary=True
    
    elif command.startswith("/at"):  
        telegramData = True
        telegramMessage = "at"
        bot.sendMessage(chatId, "High Voltage Current Measure Started")
    elif command.startswith("/ap"):  
        telegramData = True
        telegramMessage = "ap"
        bot.sendMessage(chatId, "High Voltage Current Measure Stopped")
    elif command.startswith("/dt"):  
        telegramData = True
        telegramMessage = "dt"
        bot.sendMessage(chatId, "Low Voltage Current Measure Started")
    elif command.startswith("/dp"):  
        telegramData = True
        telegramMessage = "dp"
        bot.sendMessage(chatId, "Low Voltage Current Measure Stopped")
    elif command.startswith("/shutdown"):  
        bot.sendMessage(chatId, "System is going to shutdown a bit later...")
        sleep(1)
        shutOff()
    elif command.startswith("/help"):
        text = """CurrPrb Telegram Komutları:
/hi                   # selamlama
/summary              # Son Kaydın Özeti
/range begin=x, end=y # x'den y'ye Kadar Kayıtları Göster
/at                   # High Voltage Ölçüm Başlat
/ap                   # High Voltage Ölçüm Bitir
/dt                   # Low Voltage Ölçüm Başlat
/dp                   # Low Voltage Ölçüm Bitir
/ip                   # Network Bilgileri
/shutdown             # Sistemi kapat"""
        bot.sendMessage(chatId, text)
    
    elif command.startswith("/ip"):
        netw = readLan()
        text = "IP settings:\n    MAC: {}\n    IP: {}\n".format(netw[0],netw[1]) 
        bot.sendMessage(chatId, text)
        
    
    elif command.startswith("/range "):
        params = command.split(",")
        begin=0
        end=0 
        if len(params) > 0:
            for i in params:
                if "begin" in i:
                    begin=int(i.split("=")[1])
                if "end" in i:
                    end=int(i.split("=")[1])
            
            sendSummary=True


#definitions, Functions etc
def shutOff():
    os.system("{} {}".format("shutdown", "-h now"))

def measure(ch):
    msg = [0x06,ch,0x00]
    rsp = spi.transfer(msg)
    data = ((rsp[1]*256 + rsp[2]) ) 
    #print(data)
    return data

def sayHi():
    
    text="Hi\r\n"
    ser.write(text.encode("utf-8"))
    

def recordIt(ch, values, ref, zcdState, stt, stp):
    if ch=="ch3":
    
        with open(dosya,"w") as rec:
            text="Current Probe Project\r\n"
            rec.write(text)
            text="rec Started at: {}\r\n".format(stt)
            rec.write(text)
            text="rec stopped at:{}\r\n".format(stp)
            rec.write(text)
            text="RefLevel {}\r\n".format(ref)
            rec.write(text)
            text="Channel: {}\r\n".format(ch)
            rec.write(text)
            
            
            text="CH   Time    ZCD\r\n"
            rec.write(text)
            for x, y, z in values:
                if z:
                    z = 1
                else:
                    z = 0
                text="{}\t\t{}\t\t{}\r\n".format((x - ref)*(vRef/4096)/0.08, y, z)
                rec.write(text)
        print("recorded\r\n")

    elif  ch=="ch0":
    
        with open(dosya,"w") as rec:
            text="Current Probe Project\r\n"
            rec.write(text)
            text="rec Started at: {}\r\n".format(stt)
            rec.write(text)
            text="rec stopped at:{}\r\n".format(stp)
            rec.write(text)
            text="RefLevel {}\r\n".format(ref)
            rec.write(text)
            text="Channel: {}\r\n".format(ch)
            rec.write(text)
            
            
            text="CH   Time    ZCD\r\n"
            rec.write(text)
            for x, y, z in values:
                if z:
                    z = 1
                else:
                    z = 0
                text="{}\t\t{}\t\t{}\r\n".format((x - ref)*(vRef/4096)/0.026666, y, z)
                rec.write(text)
        print("recorded\r\n")
    
 


#registers, counters etc
ac = 0
dc = 1
start = "st"
stop = "sp"
vRef = 3.448


ch0 = 0x00
ch1 = 0x40
ch2 = 0x80
ch3 = 0xC0
values=[]
cnt=0
dosya = "log/log.txt"
data = ""
readEn = False
readCh = 0
rawData = []
compute = True

telegramData = False
telegramMessage = ""
#configurations
spi = SPI("/dev/spidev0.0", 3, 2000000)
ser = serial.Serial()
ser.baudrate = 9600
ser.port = '/dev/ttyS0'
ser.open()

print("Ser state:{}\r\n".format(ser.is_open))

conf = GPIO("/dev/gpiochip0", 5, "out")
en = GPIO("/dev/gpiochip0", 6, "out")
rlHighV = GPIO("/dev/gpiochip0", 23, "out")
rlLowV = GPIO("/dev/gpiochip0", 24, "out")

zcd = GPIO("/dev/gpiochip0", 27, "in")

#HMTRP-433 Configure
en.write(False)
conf.write(True)


sabitler=sabit()
bot = telepot.Bot(sabitler.token)
MessageLoop(bot, handle).run_as_thread()
messageId = ""
sendSummary = False
begin = 0
end = 0
sayHi()

while(True):

    if sendSummary==True:
         
        makeSummary(chatId = messageId, begin=begin, end = end)
        sendSummary=False
        begin = 0
        end = 0
      
    
    if not readEn:
        refHighV = measure(ch2)
        refLowV = measure(ch1)
        
    if ser.in_waiting > 0 or telegramData == True:
        if ser.in_waiting > 0:
            raw = ser.read(ser.in_waiting)
            data = data + raw.decode("utf-8") 
        elif telegramData == True:
            telegramData = False
            data = telegramMessage
            
        if "at" in data:
            readCh = ac
            readEn = True
            compute = False
            data = ""
            stt = datetime.now()
            cnt=0
            print("High Voltage rec Started")            
        
        if "ap" in data:
            readCh = ac
            compute = True
            data = ""
            stp = datetime.now() 
            print("High Voltage rec Stopped")
        
        if "dt" in data:
            readCh = dc 
            readEn = True
            compute = False
            data = ""
            stt = datetime.now()
            cnt=0
            print("Low Voltage rec Started")            
            
        if "dp" in data:
            readCh = dc
            compute = True
            data = ""
            stp = datetime.now() 
            print("Low Voltage rec Stopped")            
            
    if readEn:
        if readCh == ac:
                       
            raw = measure(ch3)
            mt = datetime.now()
            zcdState=zcd.read()
            values.append([raw, str(mt), zcdState])
            cnt += 1
            if cnt == 100:
                rlHighV.write(True)
    
            if compute == True:
                readEn = False
                rlHighV.write(False)
                recordIt("ch3",values,refHighV,zcdState, stt, stp)
                values=[]
                compute = False

        if readCh == dc:
                       
            raw = measure(ch0)
            mt = datetime.now()
            values.append([raw, str(mt), 0])
            cnt += 1
            if cnt == 100:
                rlLowV.write(True)
    
            if compute == True:
                readEn = False
                rlLowV.write(False)
                recordIt("ch0",values,refLowV,"", stt, stp)
                values=[]
                compute = False
print("finished")
    

        

auxiliary library

Python
this file is saved as sabit.py on disk, at the same folder with main.py
class sabit:
    token = "Telegram BOT token should be placed here"
    file = "log/log.txt"
    telepotImg = "img/teleQuery.png"
    

Credits

Fikret
25 projects • 40 followers
fidenetgaraj.blogspot.com
Contact

Comments

Please log in or sign up to comment.