Kamis, 28 Oktober 2021

Raspi LCD 16x2

 import smbus
import time
 
# Define some device parameters
I2C_ADDR  = 0x27 # I2C device address
LCD_WIDTH = 16   # Maximum characters per line

# Define some device constants
LCD_CHR = 1 # Mode - Sending data
LCD_CMD = 0 # Mode - Sending command
LCD_LINE_1 = 0x80 # LCD RAM address for the 1st line
LCD_LINE_2 = 0xC0 # LCD RAM address for the 2nd line
LCD_LINE_3 = 0x94 # LCD RAM address for the 3rd line
LCD_LINE_4 = 0xD4 # LCD RAM address for the 4th line
LCD_BACKLIGHT  = 0x08  # On
#LCD_BACKLIGHT = 0x00  # Off
ENABLE = 0b00000100 # Enable bit
# Timing constants
E_PULSE = 0.0005
E_DELAY = 0.0005
#Open I2C interface
#bus = smbus.SMBus(0)  # Rev 1 Pi uses 0
bus = smbus.SMBus(1) # Rev 2 Pi uses 1

def lcd_init():
  # Initialise display
  lcd_byte(0x33,LCD_CMD) # 110011 Initialise
  lcd_byte(0x32,LCD_CMD) # 110010 Initialise
  lcd_byte(0x06,LCD_CMD) # 000110 Cursor move direction
  lcd_byte(0x0C,LCD_CMD) # 001100 Display On,Cursor Off, Blink Off 
  lcd_byte(0x28,LCD_CMD) # 101000 Data length, number of lines, font size
  lcd_byte(0x01,LCD_CMD) # 000001 Clear display
  time.sleep(E_DELAY)

def lcd_byte(bits, mode):
  # Send byte to data pins
  # bits = the data
  # mode = 1 for data
  #        0 for command
  bits_high = mode | (bits & 0xF0) | LCD_BACKLIGHT
  bits_low = mode | ((bits<<4) & 0xF0) | LCD_BACKLIGHT
  # High bits
  bus.write_byte(I2C_ADDR, bits_high)
  lcd_toggle_enable(bits_high)
  # Low bits
  bus.write_byte(I2C_ADDR, bits_low)
  lcd_toggle_enable(bits_low)

def lcd_toggle_enable(bits):
  # Toggle enable
  time.sleep(E_DELAY)
  bus.write_byte(I2C_ADDR, (bits | ENABLE))
  time.sleep(E_PULSE)
  bus.write_byte(I2C_ADDR,(bits & ~ENABLE))
  time.sleep(E_DELAY)

def lcd_string(message,line):
  # Send string to display
  message = message.ljust(LCD_WIDTH," ")
  lcd_byte(line, LCD_CMD)
  for i in range(LCD_WIDTH):
    lcd_byte(ord(message[i]),LCD_CHR)

def main():
  # Main program block
  # Initialise display
  lcd_init()
  while True:
    # Send some test
    lcd_string("RPiSpy         <",LCD_LINE_1)
    lcd_string("I2C LCD        <",LCD_LINE_2)
    time.sleep(3)
  
    # Send some more text
    lcd_string(">         RPiSpy",LCD_LINE_1)
    lcd_string(">        I2C LCD",LCD_LINE_2)
    time.sleep(3)
if __name__ == '__main__':
  try:
    main()
  except KeyboardInterrupt:
    pass
  finally:
    lcd_byte(0x01, LCD_CMD)

Raspi Insatall dan Koneksi Database New

UPDATE:

sudo apt-get update && sudo apt-get upgrade


RASPI INSATLL DATABASE SERVER:

sudo apt-get install python3-dev libmysqlclient-dev
sudo pip3 install mysqlclient

ATAU

sudo apt-get install python3-dev **default-libmysqlclient-dev**

sudo pip3 install mysqlclient


INSTALL PIP3

sudo python3-pip


INSTALL CV2

sudo apt update

sudo apt install python3-opencv


CONFIG CAMERA DLL

sudo raspi-config
df -h
sudo reboot


LCD:

 sudo raspi-config

 sudo apt-get install i2c-tools

 sudo apt-get install python-smbus

 i2cdetect -y 1

 

import MySQLdb
from time import sleep
db = MySQLdb.connect("localhost","root","","2021_deteksicitra")
cursor = db.cursor()
sql = "UPDATE `tb_pengujian`  set `status`='1',`rekapitulasi`='%s',`bobot`='%s',`kategori`='%s' where id_pengujian='%s'" % (rekapitulasi,bobot,kategori,idx)
#print(sql)
try:
cursor.execute(sql)
db.commit()
v=1
except:
db.rollback()
    db.close() 

while (True):
    ada=0
    db = MySQLdb.connect("localhost","root","","2021_deteksikentang")
    cursor = db.cursor()
    
    cursor.execute("SELECT `id_pengujian`, `nama_pengujian`, `gambar`,`status` FROM `tb_pengujian` where status='0' order by id_pengujian desc")
    for row in cursor.fetchall():
        ada=1
        id_pengujian=row[0]
        nama_pengujian=row[1]
        gambar=row[2]
        status=row[3]
        
        lokasi = PATH_UJI+gambar  
        print(lokasi)
        LoadCNN(lokasi,id_pengujian,rekapitulasi,bobot)
    time.sleep(1)
    db.close()

XRDP GUI Remote Control Raspi

 

1.Buat User baru yang memiliki password jika belum ada, misal

sudo adduser adi

sudo usermod adi -a -G pi,adm,dialout,cdrom,sudo,audio,video,plugdev,games,users,input,netdev,spi,i2c,gpio


2.Update Raspi, agar sehingga bisa kita remote jarak jauh secara FULL GUI

sudo apt update

sudo apt-get install raspberrypi-ui-mods xinit xserver-xorg

sudo reboot


3.Konfigurasi XRDP

sudo apt install xrdp 

systemctl show -p SubState --value xrdp

sudo adduser xrdp ssl-cert  


4.Jalankan RemoteControl Windows (ketik mstc)


5.Masukkan IP raspi (buat jadi satu jaringan ya...sama2 dalam router yang sama antara raspi dan laptop)







Rabu, 01 Juli 2020

OPENCV INSTALL



PYTHON OPENCV

pip install opencv-python
pip install opencv-contrib-python

atau

conda install opencv

TeSTING:
import cv2
print cv2.__version__

atau
python3 -c "import cv2"


ATAU CARA LAIN:
apt-get install -y libsm6 libxext6 libxrender-dev
pip3 install opencv-python
python3 -c "import cv2"


pip install PACKAGE_NAME
where PACKAGE_NAME can be
opencv-python (only contains main modules)
opencv-contrib-python (contains both main and contrib modules)
opencv-python-headless (same as opencv-python but without GUI functionality)
opencv-contrib-python-headless (same as opencv-contrib-python but without GUI functionality)

Perintah Dasar Mysql /UJI


PERINTAH DASAR MYSQL:

status;
select user();
SHOW VARIABLES WHERE Variable_name = 'port';
SHOW VARIABLES WHERE Variable_name = 'hostname';
select user(); 

SELECT system_user();

//PORT "mysql://user:pass@hostname:port/db"
SELECT @@port; //3306 is default

//HOSTNAME DB
SELECT @@hostname;

show variables like "%port%";

mysql -u root -p
GRANT ALL PRIVILEGES ON *.* TO 'username'@'localhost' IDENTIFIED BY 'password';
Atau
GRANT SELECT ON *.* TO 'username'@'localhost';


CREATE DATABASE dbname;
USE dbname;
CREATE TABLE example ( id smallint unsigned not null auto_increment, name varchar(20) not null, constraint pk_example primary key (id) );

INSERT INTO example ( id, name ) VALUES ( null, 'Sample data' );
DROP TABLE tablename;

PHPmyadmin di raspberry


Install cara ini:
https://www.howtoforge.com/tutorial/install-apache-with-php-and-mysql-lamp-on-debian-stretch/

JIKA ADA KENDALA...IKUTI LANGKAH SBB:

sudo apt install apache2
sudo apt install mariadb-server mariadb-client
sudo apt install php php-mysql
sudo apt install phpmyadmin

Harus disetting webserver phpmyadminnya:
PILIH apache2
BUAT phpmyadmin database =YES
HARUS KASIH password untuk phpmyadmin user DAN  strong password
JIKA DIKOSONGKAN AKAN GENERATE PASSWORD SENDIRI

UNTUK MEMAKAI phpMyAdmin GUNAKAN third user.
The root-user is not accessible to phpMyAdmin and the phpmyadmin-user doesn't have the required privileges, to administer MariaDB. 
SOLUSI:

sudo mysql

Atau kasih hak akses semua user:
sudo /usr/sbin/mysqld --skip-grant-tables

Atau update phpmyadminnya:
sudo apt update; 
sudo apt install apache2 phpmyadmin;


ATAU CARA REMOVE1 LALU INSTALL LG:
sudo apt remove mariadb-server mariadb-client phpmyadmin php --purge
sudo rm /var/www/html/phpmyadmin

CARA REMOVE2 LALU INSTALL LG:
sudo apt remove mariadb-server mariadb-client phpmyadmin php --purge
sudo apt autoremove --purge

HASILNYA SAMA ANTARA:
 /var/www/html/index.html
 /usr/share/doc/apache2/



Jika Gagal load phpmyadmin setelah install:

edit pakai nano:
nano /etc/apache2/apache2.conf

ketikkan kode sbb paling bawah:
Include /etc/phpmyadmin/apache.conf

Restart service:
sudo service apache2 restart
atau
sudo systemctl restart apache2

Jika gagal restart juga?
ln -s /etc/phpmyadmin/apache.conf /etc/apache2/sites-enabled/001-phpmyadmin
atau
sudo dpkg-reconfigure phpmyadmin


OMG JIKA TERJADI SBB:
ERROR 1045: Access denied for user: 'root@localhost' (Using
password: NO)

atau

ERROR 1045: Access denied for user: 'root@localhost' (Using
password: YES)

+++++++++++++++++++++++++
To reset your mysqld password just follow these instructions :

Stop the mysql demon process using this command :
   sudo /etc/init.d/mysql stop

Start the mysqld demon process using the --skip-grant-tables option with this command
   sudo /usr/sbin/mysqld --skip-grant-tables --skip-networking &

Because you are not checking user privs at this point, it's safest to disable networking. In Dapper, /usr/bin/mysqld... did not work. However, mysqld --skip-grant-tables did.

+++++++++++++++++++
start the mysql client process using this command
   mysql -u root
from the mysql prompt execute this command to be able to change any password
   FLUSH PRIVILEGES;
Then reset/update your password
   SET PASSWORD FOR root@'localhost' = PASSWORD('password');
If you have a mysql root account that can connect from everywhere, you should also do:
   UPDATE mysql.user SET Password=PASSWORD('newpwd') WHERE User='root';

++++++++++++++++++
Alternate Method:
   USE mysql
   UPDATE user SET Password = PASSWORD('newpwd')   WHERE Host = 'localhost' AND User = 'root';
 
And if you have a root account that can access from everywhere:
   USE mysql
   UPDATE user SET Password = PASSWORD('newpwd')   WHERE Host = '%' AND User = 'root';
 
For either method, once have received a message indicating a successful query (one or more rows affected), flush privileges:

FLUSH PRIVILEGES;
Then stop the mysqld process and relaunch it with the classical way:

sudo /etc/init.d/mysql stop
sudo /etc/init.d/mysql start

When you have completed all this steps ,you can easily access to your mysql server with the password you have set in the step before.
An easy way to have a full control of your mysql server is phpmyadmin (www.phpmyadmin.net), software made in php that can give you a web interface that can be very usefull to people that havent got a lot of confidence with bash .

To install phpmyadmin on you server you will need to have 4 things:

web server apache
php
mysql server/mysql client installed
php_mysql support for apache
All packages can be found browsing synaptic.

JIKA MASIH GATOT:
sudo apt-get --purge remove mysql-server mysql-common mysql-client
sudo apt-get install mysql-server mysql-common mysql-client

In the next step be sure to chance the your-new-password with the password you want!

mysqladmin -u root password your-new-password
sudo /etc/init.d/mysql restart

mysql -u root -p
You should now be logged in as root. Make sure to notedown your password! Thanks to Illuvator for posting this method in the ubuntu forum.

The Easiest Method

sudo dpkg-reconfigure mysql-server-N.N



+++++++++++++++++

JIKA LOOP ERROR:

You have to reconfigure phpmyadmin, reset MySQL password.

Reconfigure phpmyadmin
Ctrl + Alt + T to launch terminal
sudo dpkg-reconfigure phpmyadmin
Connection method for MySQL database for phpmyadmin: unix socket
Name of the database's administrative user: root
Password of the database's administrative user: mysqlsamplepassword
MySQL username for phpmyadmin: root
MySQL database name for phpmyadmin: phpmyadmin
Web server to reconfigure automatically: apache2
ERROR 1045
ignore
sudo dpkg-reconfigure mysql-server-5.5
New password for the MySQL "root" user: mysqlsamplepassword
Repeat password for the MySQL "root" user: mysqlsamplepassword


SOLUSI:
mysql -u root -p

Entered the root password Created a new user using the following command:

CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'some_very_complex_password';

Granted all permissions to newuser:

GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';
FLUSH PRIVILEGES;

CEK ULANG:
By "rootuser" you mean the MySQL root user, not the system root user, right?

During the installation of mysql-server, the MySQL root account is created and its password is stored in /etc/mysql/debian.cnf.

The configuration files of phpMyAdmin are stored in /etc/phpmyadmin.


echo "UPDATE mysql.user SET plugin = 'mysql_native_password' WHERE user = 'root' AND plugin = 'unix_socket';FLUSH PRIVILEGES;" | mysql -u root -p


I installed MySQL using synaptic manager. Didn't have to enter a root password. The command:

mysqladmin -u root password NEWPASSWORD

Edit:
/etc/phpmyadmin/config.inc.php
Not:
/usr/share/phpmyadmin/config.inc.php

echo "UPDATE mysql.user SET plugin = 'mysql_native_password' WHERE user = 'root' AND plugin = 'unix_socket';
FLUSH PRIVILEGES;" | mysql -u root -p



https://www.raspberrypi.org/forums/viewtopic.php?t=216346
https://help.ubuntu.com/community/MysqlPasswordReset
https://askubuntu.com/questions/34409/unable-to-login-to-phpmyadmin-with-the-root-user

Selasa, 06 November 2018

Raspi sebagai LCD Proyektor

Ceritanya

Dosen login....dia scan semua PC di jaringannya...muncullah ip ip computer para siswanya
trus dia piih salah satu untuk presentasi....
maka pc yang dia klik akan tertuju di layar utama...

Konsepnya adalah sama dengan remote desktop...hanya ini di modif seakan2:
LCD proyektor,.........

++++++++++++++++++++++++++++++++++++++++++++++++++


metode u aplikasi Impelemantasi share desktop raspberry PI untuk LCD projector adalah menggunakan metode pencocokan content atau biasa di sebut dgn sequential search

cara kerjanya:
1.admin/dosen/moderator dosen akan menscan IP di jaringan kelas tsb
sehingga akan ketahuan IP mana saja yang aktif dan yang tidak aktif
2.admin/dosen/moderator memilih ip yang akan di munculkan layar desktopnya ke monitor
3.disini diperlukan admin/moderator/dosen agar tidak terjadi rebutan klik ip yang akan aktif
4.konsep koneknya adalah, dengan terlebih dahulu mendiskonek perangkat /laptop sebelumnya baru autokonek ip laptop terpilih
5.ada tombol juga reset all yang artinya diskonesi ke semua pc client dari layar monitor
6.semua aktivitas akan tercatat di tabel log

keterbatasan:
1.aplikasi hanya bisa diterapkan dalam 1 jaringan network/satu subnetmask
2.pengenalan antar laptop adalah menggunakan ip address sehingga setiap laptop agar mudah dikenali siapa pemiliknya maka harus di daftarkan dahulu
3.harus install library apliaksi di client juga

novelty/nilai kebaruan aplikasi ini dari sebelumnya:
1.aplikasi berbasis cient server sehingga mudah memantaunya bisa berbasis desktop, mobile(android), web
2.adanya tabel .log u menyimpan semua aktivitas
3.adanya fitur scan sehingga pc/laptop bisa ditambah atau dikurangkan secara dinamis


Nah ino code veri dosennya:


 <?php

if(isset($_GET["scan"])){
$sql="insert into tb_command values('scan')";
process($conn,$sql);
                echo "<script>alert('Please wait 30 seconds then press OK button')</script>";
                //sleep(30);
                die("<script>location.href='?mnu=controlpanel'</script>");
}

if(isset($_GET["close"])){
  $sql="update tb_status set status='standby'";// where ip='$ip'
        process($conn,$sql);

  $sql="insert into tb_command values('close')";
process($conn,$sql);
die("<script>location.href='?mnu=controlpanel'</script>");
}

if(isset($_GET["st"])){
$kode_status=$_GET["kode"];
$ip=$_GET["id"];
$st=$_GET["st"];

$sql="update tb_status set status='$st' where ip='$ip'";
process($conn,$sql);

if($st=="on"){
//$sql="insert into tb_close values('close')";
$sql="update tb_status set status='$st' where ip='$ip'";
                process($conn,$sql);

$sql="insert into tb_command values('on#$ip')";
process($conn,$sql);
                echo "<script>alert('Your session will expire in 15 minutes')</script>";
die("<script>location.href='?mnu=controlpanel'</script>");
}
else{//standby
$sql="insert into tb_command values('close')";
process($conn,$sql);
die("<script>location.href='?mnu=controlpanel'</script>");
}
}
?>

<div id="accordion">
  <h3>Data</h3>
  <div><p style="text-align:left;">

    <a href="tightvnc-2.8.8-gpl-setup-32bit.msi">Download software presentasi (Win32)</a></span></p>
    <span style="float:right;"> <a href="tightvnc-2.8.8-gpl-setup-64bit.msi">Download software presentasi (Win64)</a></span>
  <br>

<table width="50%" class="table table-bordered table-striped table-hover js-basic-example dataTable">
  <tr bgcolor="#036">
    <th width="3%"><center>No</th>
    <th width="30%"><center>IP</th>
    <th width="15%"><center>Status</th>
    <th width="10%"><center>Jam</th> 
    <th width="10%"><center>PLAY</th> 
  </tr>
<?php
  $sql="select * from `$tbstatus` order by `kode_status` desc";
  $jum=getJum($conn,$sql);
if($jum > 0){
$no=1;
$arr=getData($conn,$sql);
foreach($arr as $d) {
$kode_status=$d["kode_status"]; ;
$jam=$d["jam"];
$ip=$d["ip"];
$status=$d["status"];
$color="#dddddd";
if($no %2==0){$color="#eeeeee";}
echo"<tr bgcolor='$color'>
<td>$no</td>
<td align='center'>$ip</td>
<td align='center'>$status</td>
<td align='center'>$jam</td>";

if($status=="on"){
echo"<td align='center'>
<a href='?mnu=controlpanel&st=standby&kode=$kode_status&id=$ip'><input type='button' value='$status'></a>
</td>";
}
else{
echo"<td align='center'><a href='?mnu=controlpanel&st=on&kode=$kode_status&id=$ip'><input type='button' value='$status'></a></td>";
}

echo"</tr>";

$no++;
}//while
}//if
else{echo"<tr><td colspan='7'><blink>Maaf, Data status belum tersedia...</blink></td></tr>";}
?>
</table>
</div>


</div>
<a href='?mnu=controlpanel&scan=scan'><input type='button' value='SCAN IP'></a>
<a href='?mnu=controlpanel&close=close'><input type='button' value='CLOSE ALL'></a>

Sedang di raspinya:


import MySQLdb
from time import gmtime, strftime
from random import randint
import time
import subprocess
import os
import os, sys

data1=""
data2=""
data3=""

start=0
kon=1
paketimer=False

while kon==1:

    sql="SELECT * FROM tb_command"
    db = MySQLdb.connect("localhost","dian","12345","db_matakuliah")
    cursor = db.cursor()
    proses=0

    cursor.execute(sql)
    res = cursor.fetchall()
    mdata=""
    time.sleep(1)

    if paketimer==True:
      if time.time() > start + 900:
        os.system("pkill vncviewer")
        sql = "UPDATE tb_status set status='standby', keterangan='-' where status='on'"
        try:
           cursor.execute(sql)
           db.commit()
        except:
           db.rollback() 

    for row in res :
        mdata =row[0]

        print(mdata)
        data = mdata.split("#")

        if len(data)==1:
            data1=data[0]
        elif len(data)==2:
            data1=data[0]
            data2=data[1]
        elif len(data)==3:
            data1=data[0]
            data2=data[1]
            data3=data[2]
         
        proses =0
        if len(data)==1: 
            if data1 == "scan": #scan
                print "SCAN"
                proses=1
                #SCAN

                sql="Truncate tb_status"
                try:
                     cursor.execute(sql)
                     db.commit()
               
                except:
                     db.rollback()
               
                with open(os.devnull, "wb") as limbo:
                    for n in xrange(100, 150):
                        ip="192.168.1.{0}".format(n)
                        result=subprocess.Popen(["ping", "-c", "1", "-n", "-W", "1", ip],
                        stdout=limbo, stderr=limbo).wait()
                        if result:
                            print ip, "offline"
                        else:
                            print ip, "online"
                            tanggal=strftime("%Y-%m-%d", gmtime())
                            jam=strftime("%H:%M:%S", gmtime())
                            sql="INSERT INTO `tb_status` (`tanggal` ,`jam` ,`ip` ,`status` ,`keterangan`) VALUES('%s','%s','%s','%s','%s')" % (tanggal,jam,ip,'standby','-')
                            print sql
                            try:
                                cursor.execute(sql)
                                db.commit()
                            except:
                                db.rollback()
            elif data1 == "close":
                  proses=1
                  print "CLOSE"
                  os.system("pkill vncviewer")
                  paketimer=False

        elif len(data)<=3: 
            if data1 == "on": #on#192.168
                proses=1

                ip=data2
                tanggal=strftime("%Y-%m-%d", gmtime())
                jam=strftime("%H:%M:%S", gmtime())
                keterangan=data1

                sql="Truncate tb_command"
                try:
                     cursor.execute(sql)
                     db.commit()

                except:
                     db.rollback()


                sql ="UPDATE `tb_status` set `status`='%s', `jam`='%s', `tanggal`='%s', `keterangan`='%s' where ip='%s'" % ('on',jam,tanggal,keterangan,ip)
                #print (sql)
                try:
                     cursor.execute(sql)
                     db.commit()
                except:
                     db.rollback()

                #AL = os.system("./vnc2.sh "+ ip)
                subprocess.Popen(["./vnc2.sh", ip])
                paketimer=True
                start = time.time()

             
        print "OK-LOPS----"
        if proses==1:
            sql="Truncate tb_command"
            try:
                 cursor.execute(sql)
                 db.commit()
               
            except:
                 db.rollback()
    cursor.close ()
    db.close () 



+++++++++++++
sedang Bash Shell nya sbb: vnc2.sh

#!/bin/bash

ssvnc -cmd -viewer -scale 0.75  -fullscreen $1

+++++++++++++
tabelnya sbb:

CREATE TABLE `tb_command` (
  `command` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


CREATE TABLE `tb_status` (
  `kode_status` int(15) NOT NULL,
  `tanggal` date NOT NULL,
  `jam` time NOT NULL,
  `ip` varchar(20) NOT NULL,
  `status` varchar(15) NOT NULL,
  `keterangan` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


INSERT INTO `tb_status` (`kode_status`, `tanggal`, `jam`, `ip`, `status`, `keterangan`) VALUES
(1, '2018-10-30', '15:50:51', '192.168.1.8', 'standby', '-'),
(2, '2018-10-30', '15:50:51', '192.168.1.9', 'standby', '-'),
(3, '2018-10-30', '15:59:49', '192.168.1.10', 'on', 'on'),
(4, '2018-10-30', '15:50:52', '192.168.1.11', 'standby', '-');



Ok mudah yaaaaaaaaaaaaaaaaaaaaaaaaaa