lördag 12 september 2015

Simple VB code to send message (note) to all devices with Pushbullet API.

Keeping it short, this is simple working example how to send note from VB program to your device(s) with Pushbullet.
You will need the token from Pushbullet settings page and copy it to the code.
For the test project use the following design (items are with default names):

  • Form
  • Button
  • RichTextBox

Imports needed for the code:

Imports System
Imports System.IO
Imports System.Net
Imports System.Text

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim token As String = " **** your token from Pushbullet ****"
        Dim title As String = "Title goes here"
        Dim body As String = "Message body goes here"
       

        Try
            ' Create a request using a URL that can receive a post.'
            Dim Request As HttpWebRequest = CType(WebRequest.Create("https://api.pushbullet.com/v2/pushes"), HttpWebRequest)

            ' Set the Method property of the request to POST.'
            Request.Method = "POST"

            ' Create POST data and convert it to a byte array.'
            Dim postData As String = "{""type"": ""note"", ""title"": """ & title & """, ""body"": """ & body & """}"
            Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)

            ' Set the ContentLength property of the WebRequest.'
            Request.ContentLength = byteArray.Length
            ' Set the ContentType property of the WebRequest.'
            Request.ContentType = "application/json"
            ' Add the token to header.'
            Request.Headers.Add("Access-Token", token)
            ' Get the request stream.'
            Dim dataStream As Stream = Request.GetRequestStream()
            ' Write the data to the request stream.'
            dataStream.Write(byteArray, 0, byteArray.Length)
            ' Close the Stream object.'
            dataStream.Close()
            ' Get the response.'
            Dim response As WebResponse = Request.GetResponse()
            ' Get the stream containing content returned by the server.'
            dataStream = response.GetResponseStream()
            ' Open the stream using a StreamReader for easy access.'
            Dim reader As New StreamReader(dataStream)
            ' Read the content.'
            Dim responseFromServer As String = reader.ReadToEnd()
            ' Show result in RichTextBox.'
            RichTextBox1.Text = responseFromServer

            ' Clean up the streams.'
            reader.Close()
            dataStream.Close()
            response.Close()

            ' Error handling - write to Immediate window with debug.print'
        Catch a As ArgumentException
            Debug.Print(a.Message)
        Catch a As WebException
            Debug.Print(a.Message)
            If a.Status = WebExceptionStatus.ProtocolError Then
                Debug.Print("Status Code : {0}", CType(a.Response, HttpWebResponse).StatusCode)
                Debug.Print("Status Description : {0}", CType(a.Response, HttpWebResponse).StatusDescription)
                Debug.Print("Server : {0}", CType(a.Response, HttpWebResponse).Server)
            End If
        Catch a As Exception
            Debug.Print(a.Message)
        End Try

    End Sub


References:

lördag 22 november 2014

iRobot Roomba IR-remote: Send CLEAN command


Intro

The cheaper models of iRobot Roomba -I have model 620- doesn't come with a scheduler. So you have to manually reach down and push the clean-button for it to start clean your house.
Roomba provides an infrared remote control to start up the cleaner. That is what we going to mimic here.

I have summarized 2 articles that I've found from the internet according this remote. The other is Virtual Wall with 12F683 and the other is "Tiny Remote" for Roomba, which uses other PIC and doesn't have source code written in C. Links to both you can find at the bottom of this article.

Roombas IR-remote works on 38Khz carrier and the bits for 1 and 0 are following:


The code consist of 8 bits and for CLEAN it is following: 10001000
For more codes refer to "Tiny Remote" site.


The software

When powering up the circuit, the program sends "CLEAN"-command 5 times, with 32ms delay between commands and then falls asleep. I did some experiment with different scenarios, anything from having it send the code once and looping it for infinite time. When sending once, Roomba didn't always react to the command. And to send it longer period, it became confused and sometimes stopped and started again the cleaning cycle. Also the delay between the code had some strange behaviors, so putting up 8 bits times 4ms = 32ms, did the thing. With another words the code and delay between them are equal length. Whole 5 times cycle takes therefore 5x32ms + 4x32ms (last delay doesn't count) = 288ms.

The code is pretty forward and easy to follow. Here is flow chart to explain how it works:


And the code itself:
 /*   
  * File:  main.c  
  * Author: Juice  
  *  
  * Created on den 18 november 2014, 23:58  
  */  
 #include <xc.h>  
 #ifndef _XTAL_FREQ  
  #define _XTAL_FREQ 2000000  
 #endif  
 #define PWM_OFF CCP1CON = 0x10  
 #define PWM_ON CCP1CON = 0x1c  
 #define BURST_COUNT 2         // How many IR bursts to send (repeat of pattern 1000)  
 #define LOOP_COUNT 5          // How many times to send code  
 int bit_high(void) //Subroutine for bit 1 = 3ms on, 1ms off  
 {  
        PWM_ON;  
       __delay_us(3000);  
       PWM_OFF;  
       __delay_us(1000);  
 }  
 int bit_low(void) //Subroutine for bit 0 = 1ms on, 3ms off  
 {  
        PWM_ON;  
       __delay_us(1000);  
       PWM_OFF;  
       __delay_us(3000);  
 }  
 int main(void)  
 {  
   int i;  
   int l;  
   OSCCON = 0x51;           // Internal 2MHz osc.  
   ADCON0 = 0;             // all pins digital  
   ANSEL = 0;             // all pins digital  
   CMCON0 = 7;             // Comparators off.  
   TRISIO = 0;             // all output  
   GPIO = 0;              // all pins low  
   PR2 = 0b00001100 ;         // Set up PWM for roughly 38kHz  
   T2CON = 0b00000100 ;  
   CCPR1L = 0b00000110 ;  
   PWM_OFF;  
   PSA = 0;              // Don't use Timer0 prescalar  
   WDTCON = 0b00010000;        // Prescalar = 1000 = 8192 = 272ms  
   l = LOOP_COUNT;  
   while( l-- )  {          // how many times to send code.  
                     // sending 2 times 1000, since code is 10001000  
     i = BURST_COUNT;  
     while( i-- )  
     {     
       bit_high();         // send the first 1  
       int x;           // loop 3 times bit_low  
       for ( x = 0; x < 3; x++ ) {  
         bit_low();       //send 0  
        }  
     }  
     __delay_ms(32);         // delay between commands 3+1ms=4ms for one bit. 8bit * 4ms = 32ms.  
   }  
  asm("sleep") ;            // Put processor to sleep.  
  }  

To edit the code and compile, you need MPLAB X IDE v2.25 and MPLAB® XC8 Compiler v1.33B (Links at the bottom of this article.).

For those who doesn't need to edit the source code, here is ready compiled HEX-file for flashing: Roomba_clean.HEX

And for flashing the PIC, there are many hardwares to choose from. One of the cheapest and probably most popular is the K150 USB PIC Programmer, which you can purchase for example from Ebay.


The hardware


Parts list:
  • Microship PIC 12F683 8-Pin Flash-Based, 8-Bit CMOS Microcontroller
  • R1 Resistor 330ohm 0.25W
  • R2 Resistor 40ohm 0.25W
  • R3 Resistor 100ohm 0.25w * see text below
  • C1 Capacitor 100nF
  • T1 Transistor 2N3904 (I tested with BC549, 550, 560. The PIC is also cabable to power up LED directly, but with this setup we push around 85mA thru the IR-LED, to provide enough range to the system.)
  • D1 IR-LED 940nm
It can be build easily on small Veroboard. Nothing critical here.
Mount the C1 as near as possible to the PIC pins 1 and 8 (Decoupling capacitor).
The input voltage can be between 3-5,5V. Reduce the R2 slightly (~22-27 ohms) if using 3V.







Bonus: Tellstick


For Tellstick users this circuit can be powered from USB wall charger and compatible receiver (Nexa etc.).
The R3 might be needed to drain the wall charger capacitors out. Otherwise it can take few minutes before the circuit powers off and you can start it again. (In case Roomba won't start and you like to repeat the command.)

Tellsdus Live! event handler. In swedish, but pretty straightforward.

Just create event on Tellstick to shutdown the receiver few seconds after it turns on.

Thats it!
Please feel free to comment and even link/show your own project in case this was any help at all!

P.S För svenska besökare kan jag även tänka mig att sälja färdigflashad PIC för en billig peng.


References / Thanks to:
http://www.enide.net/webcms/?page=tiny-remote
http://misc.ws/2014/08/09/diy-virtual-wall-for-roomba-part-two/
http://www.microchip.com/wwwproducts/Devices.aspx?dDocName=en010115
http://www.microchip.com/pagehandler/en-us/family/mplabx/
http://www.microchip.com/pagehandler/en-us/devtools/mplabxc/home.html



onsdag 2 april 2014

Overclocking AsicMiner Blade v2



l'appétit vient en mangeant - the appetite grows while eating

You want to push up the hashing power just little more to get more shares? Well, yes, who wouldn't?


After 'Googling' around little, I found this blog about overclocking AsicMiner Blade v2:
http://8rowsof4.blogspot.se/2014/02/overclocking-asicminer-blade-v2-green.html

I contacted the author and we had nice email thread, discussing and explaining the things around the procedures.
In just 10 days (from USA to Sweden, Europe) I got 4 kits I ordered.
Nicely packaged and with some candy too!

The soldering procedure requires steady hand and good soldering iron. I got one with 1 mm tip, which was perfect for this. But otherwise it is not hard to do, if you have some experience.
So if you have any plans to get some extra from your Blades, just do it!
Remember also that they will generate more heat, so chipside cooling is much recommended.

This blog entry wont go in to deep about how to do it, for that I suggest you read his excellent blog with detailed instructions.


Just showing few details from the work:

I used some 8,8 x 8,8 mm IC heat sinks for chip side cooling.
(Note: use silicone heatsink plaster as less as possible. Just enough it fastens, for best cooling.)


Solder iron tip.

2 of the 8 resistors that needs to be changed. R113 & R101

15 AMP fuse in place.

Oscillator jumper and new oscillator in place.

And finally the results after running bit over 13h. The efficiency might go up with better cooling. 13ghs is quite acceptable so far!


måndag 10 mars 2014

Instant trade all your NMC to BTC on CEX.io
Console application [VB + Newtonsoft Json library]

This little application checks your NMC (NameCoin) balance,  gets the last price from ticker and places order* on all your NMC to sell for BTC.

*) It places the order, but doesn't check if and when it is completed. Ususally it goes thru instantly when using the last price.

If you want to get other price from ticker to use, you can use following parameters for that:

last - last BTC price
high - last 24 hours price high
low - last 24 hours price low
bid - highest buy order
ask - lowest sell order
Change green coloured the text in code.

You'll need Newtonsoft JSON library for parsing the json response from server.
http://json.codeplex.com/

1. Make new Console application in VB and copy/paste this code below.
2. Reference the Newtonsoft.dll to application
3. Fill in (see the corresponding colours in the code) your username, API key and API secret from CEX.io -> Profile -> API
When creating the API key you must check at least the Account balance and Place order checkboxes.
API secret is shown before you activate the key, be sure to copy that, it will not be shown after the activation!

Imports System
Imports System.IO
Imports System.Security.Cryptography
Imports System.Net
Imports System.Text
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq

Module Module1

    Sub Main()

        Dim balance As String = getdata("https://cex.io/api/balance/")
        Dim price As String = getdata("https://cex.io/api/ticker/NMC/BTC")

        Dim pricevalues As Newtonsoft.Json.Linq.JObject
        pricevalues = JObject.Parse(price)

        Dim balancevalues As Newtonsoft.Json.Linq.JObject
        balancevalues = JObject.Parse(balance)

        Dim bal, last As String
        Try
            bal = balancevalues.GetValue("NMC")("available")
            last = pricevalues.GetValue("last")
        Catch ex As Exception
            Console.WriteLine(ex.ToString)
        End Try

        drawline()
        Console.WriteLine(Now.ToLongTimeString)
        Console.WriteLine("Account balance NMC: " & bal & " NMC")
        Console.WriteLine("Last price 1 NMC = " & last & " BTC")
        drawline()

        If CDbl(bal) > 0 Then
            Console.WriteLine("ORDER PLACED - Server response:")
            Console.WriteLine(getdata("https://cex.io/api/place_order/NMC/BTC", bal, last))
        Else
            Console.WriteLine("Balance NMC = 0, no order placed")
        End If

        Console.ReadKey()

    End Sub

    Sub drawline()
        Dim strC As String
        strC = New String("-"c, 80)
        Console.WriteLine(strC)
    End Sub

    Function getdata(ByVal URL As String, Optional ByVal bal As String = "", Optional ByVal last As String = "")

        Dim G_USERNAME As String = "username"
        Dim G_APIKEY As String = "API key"
        Dim G_APIKEY_SECRET As String = "API secret"
        Dim nonce = Get_Nonce()
        Dim message As String
        Dim signature = hash_sha256(nonce & G_USERNAME & G_APIKEY, G_APIKEY_SECRET)

        If bal = "" Or last = "" Then
            message = "key=" & G_APIKEY & "&" & "nonce=" & nonce & "&" & "signature=" & signature
        Else
            message = "key=" & G_APIKEY & "&" & "nonce=" & nonce & "&" & "signature=" & signature & "&type=sell&price=" & last & "&amount=" & bal
        End If

        getdata = sourcestring(URL, message)

    End Function

    Function hash_sha256(ByVal StringToHash, ByVal KeyForHash) As Object

        Dim sha256, ObjUTF8, hmac
        ObjUTF8 = CreateObject("System.Text.UTF8Encoding")
        sha256 = CreateObject("system.security.cryptography.HMACSHA256")
        sha256.Key = ObjUTF8.GetBytes(KeyForHash)
        hmac = sha256.ComputeHash(ObjUTF8.GetBytes(StringToHash))
        sha256.Clear()

        Dim a
        Dim b = hmac.length
        For Each c As Byte In hmac
            a += Strings.Right("0" & Conversion.Hex(c), 2)
        Next
        Return UCase(a)
    End Function

    Function Get_Nonce() As Long
        Dim centuryBegin As Date = #1/1/2014#
        Dim currentDate As Date = Date.Now
        Dim elapsedTicks As Long = currentDate.Ticks - centuryBegin.Ticks
        Return elapsedTicks
    End Function

    Function sourcestring(ByVal url, ByVal message) As String

        Dim request As WebRequest = WebRequest.Create(url)
        request.Method = "POST"
        Dim byteArray As Byte() = Encoding.UTF8.GetBytes(message)
        request.ContentType = "application/x-www-form-urlencoded"
        request.ContentLength = byteArray.Length
        Dim dataStream As Stream = request.GetRequestStream()
        dataStream.Write(byteArray, 0, byteArray.Length)
        dataStream.Close()

        Try
            Dim response As WebResponse = request.GetResponse()

            ' BEGIN DEBUG --------------------Uncomment below to get debuginfo------------------------

            'drawline()
            'Console.WriteLine("==== Debug info ====")
            'Console.WriteLine(url.ToString)
            'Console.WriteLine(Replace(message, "&", System.Environment.NewLine))
            'Console.WriteLine("HTTP STATUS: " & CType(response, HttpWebResponse).StatusDescription)

            '-----------------------------------------------------------------------------------------
            dataStream = response.GetResponseStream()
            Dim reader As New StreamReader(dataStream)
            Dim responseFromServer As String = reader.ReadToEnd()
            Return responseFromServer

            reader.Close()
            dataStream.Close()
            response.Close()
        Catch ex As Exception
            Console.WriteLine(ex.ToString)
            Return Nothing
        End Try

    End Function

End Module

NOTE: Server response is not parsed, but it is fully readable.

onsdag 5 mars 2014

Slush mining proxy as service in Windows

This is simple tutorial about how to start Slush mining proxy as service on Windows PC.
For reference I've used this on Windows 2003 server, but it should be same on other versions as well. Basic knowledge of Windows and it's components is required.

Things we'll need:
After we have installed the Resource Kit, the 2 files (srvany.exe & instsrv.exe) can be found at: C:\Program Files\Windows Resource Kits\Tools\ 
I suggest you copy these 2 files to C:\Windows\system32\ for easier typing on the command shell later on.

1. Start command shell (cmd.exe) and browse to C:\Windows\system32\
2. Install the "custom" service by typing following command:
    instsrv ANYNAME C:\Windows\system32\srvany.exe    
Note that you must specify full path to the srvany.exe, even that we are in same folder. You can  (and should) of course replace ANYNAME with your own. At this point we only create the custom service and only specifying its name. I used Proxyservice as name in this example. 
    Screenshot above shows whole procedure.
    Note that the first try without full path gives error, so we try again with full path and get the right response.



3. Open Registry Editor by typing regedit on the "Run..." box under the Start-menu.
- I'll call the registry keys as "folder" in the following, even they are not really folders, but the icon shows them as ones.
4. Browse to: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Proxyservice (The last "folder" is our desided name for the service.)
Now we need to create few things in the "folder" before we can finally start our new service:
- a key called Parameters and
- two string values called Application and AppParameters
5. Right-click the "folder" Proxyservice and choose New -> Key. A new "folder" appears. Rename this New key #1 to Parameters
6. Right-click the "folder" Proxyservice again and choose this time New -> String Value.
Repeat that once more. Now there should be New Value #1 and New Value #2 inside the Parameters key. Rename these to Application and AppParameters
7. The Application value points to the application we want to start as service, in our case it is the mining_proxy.exe. Edit the value to C:\miningproxy\mining_proxy.exe
8. The AppParameters are the same command line parameters that you can use when starting mining proxy from batch-file (.bat). If you're mining at Slush's pool, you can leave this empty, as the mining_proxy connects to Slush as default.
In this example I used ghash.io pool, so we edit the value to -o uk1.ghash.io -q
Now that everything has been set, the key and its strings should look like following:








9. Go to Control Panel -> Administrative Tools -> Services and you should find the service there with name Proxyservice. If everything is correct, try start the service and it should run finally! 
You can see it running on Task Manager with name mining_proxy.exe
(Just remember check the box "show processes from all users" to see it.)
P.S. For those who can't bother to edit Registry by own, here is .reg file for that:
Copy it to emtpy textfile and name it whatever.reg 
Note that there must be an empty line at the bottom of the file and yet again, replace Proxyservice with the name you desided earlier, if you changed it.

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Proxyservice\Parameters]
"Application"="C:\\miningproxy\\mining_proxy.exe"
"AppParameters"="-o uk1.ghash.io -q"